Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract zip file without folder python

Tags:

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 ?

like image 502
Brook Gebremedhin Avatar asked Oct 12 '25 22:10

Brook Gebremedhin


2 Answers

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.

like image 147
Sven Krüger Avatar answered Oct 14 '25 11:10

Sven Krüger


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)
like image 21
John Zwinck Avatar answered Oct 14 '25 13:10

John Zwinck