4

I am currently using extratall function in python to unzip, after unziping it also creates a folder like: myfile.zip -> myfile/myfile.zip , how do i get rid of myfile flder and just unzip it to the current folder without the folder, is it possible ?

cs95
  • 379,657
  • 97
  • 704
  • 746
  • I'd recommend using `shutil.move`, specify a source directory, and destination (the current), and then `os.rmdir` to delete your temp directory. – cs95 Oct 26 '17 at 12:50
  • Does this answer your question? [Extract files from zip without keeping the structure using python ZipFile?](https://stackoverflow.com/questions/4917284/extract-files-from-zip-without-keeping-the-structure-using-python-zipfile) – Boketto Sep 15 '22 at 09:34

2 Answers2

1

I use the standard module zipfile. There is the method extract which provides what I think you want. This method has the optional argument path to either extract the content to the current working directory or the the given path

import os, zipfile

os.chdir('path/of/my.zip')

with zipfile.ZipFile('my.zip') as Z :
    for elem in Z.namelist() :
        Z.extract(elem, 'path/where/extract/to')

If you omit the 'path/where/extract/to' the files from the ZIP-File will be extracted to the directory of the ZIP-File.

Sven-Eric Krüger
  • 1,277
  • 12
  • 19
0
import shutil

# loop over everything in the zip
for name in myzip.namelist():
    # open the entry so we can copy it
    member = myzip.open(name)
    with open(os.path.basename(name), 'wb') as outfile:
        # copy it directly to the output directory,
        # without creating the intermediate directory
        shutil.copyfileobj(member, outfile)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Please add an explanation to your answer – heinst Oct 26 '17 at 13:21
  • Welcome to Stack Overflow @heinst. Luckily Joris already added some comments to the code so you can follow along. – John Zwinck Oct 26 '17 at 13:26
  • 1
    What do you mean welcome to stack overflow? I was in the Moderator queue and it did not have any comments so I asked you to make some. Dont have to be rude man – heinst Oct 26 '17 at 14:23
  • @JohnZwinck , currently myzip.namelist() returns, something like {folder1/file1.txt, folder1/fil2.txt, folder1/file3.txt} , how could i only return it like {file1.txt, file2.txt, fil3.txt} without the folder directory ? – Brook Gebremedhin Oct 31 '17 at 18:17
  • @BrookGebremedhin: You use `os.path.basename` for that - I added it to my answer. – John Zwinck Nov 06 '17 at 04:31