4

How to extract a zip file using python when zip file present in different directory where script file present. I try this ,but i got error because source path is not accepted ,try to solve me this problem.

from zipfile import ZipFile

def func(source, target):
    with ZipFile('source', 'target'):
        ZipFile.Extractall('target')
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
Sudhakar
  • 57
  • 1
  • 1
  • 8
  • Possible duplicate of [Extracting .zip in python](https://stackoverflow.com/questions/46994589/extracting-zip-in-python) – sophros Jul 09 '19 at 07:18

3 Answers3

7

For just unpacking, shutil should suffice:

import shutil
shutil.unpack_archive('path-to-zipfile')
00schneider
  • 698
  • 9
  • 21
5

Use this code. To move through directories you could either hard code the directory where your script is present or you could toggle through the directories using simple commands such as "../" to move out of the given directory or "/" to move inside a folder in the directory. For example - "../script.py" or "/folder/script.py". Similarly you can use this to find your .zip file.

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")
Prakhar Sood
  • 159
  • 1
  • 10
1

You'll have to check for source path of the zip file which is relative to your current working directory. To know your current working directory you can try

import os print(os.getcwd())

zip - Unzipping files in python

relative-paths-in-python

Naman Chikara
  • 164
  • 14