Brook Gebremedhin
Brook Gebremedhin

Reputation: 43

extract zip file without folder python

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 ?

Upvotes: 4

Views: 6057

Answers (2)

John Zwinck
John Zwinck

Reputation: 249153

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)

Upvotes: 0

Sven-Eric Krüger
Sven-Eric Krüger

Reputation: 1327

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.

Upvotes: 2

Related Questions