0

I'm running the following script to unzip several zipfiles from a directory:

import os
from zipfile import ZipFile

dir_name = f"C:/my_path/zip/{name}"

def main():

    for item in os.listdir(dir_name):
        with ZipFile(item, 'r') as zipObj: 
            listOfFileNames = zipObj.namelist()
            for fileName in listOfFileNames: 
                if fileName.endswith('.csv'):
                    for i in fileName:
                        zipObj.extract(fileName, f"C:/my_path/csv/{name}")

if __name__ == '__main__':
    main()

The point is that I've confirmed a hundred times that the zip files are stored in the right path but I can't run the script but I did succesfully in another computer (?)

What I am doing wrong?

EDIT:

This is the entire error message:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-6-7f26de4464fe> in <module>
     18 
     19 if __name__ == '__main__':
---> 20     main()

<ipython-input-6-7f26de4464fe> in main()
     10 
     11     for item in os.listdir(dir_name): # Iterate over the zip file
---> 12         with ZipFile(item, 'r') as zipObj: # Create a ZipFile Object and load sample.zip in it
     13             listOfFileNames = zipObj.namelist() # Get a list of all archived file names from the zip
     14             for fileName in listOfFileNames: # Iterate over the file names

C:\Anaconda\lib\zipfile.py in __init__(self, file, mode, compression, allowZip64)
   1111             while True:
   1112                 try:
-> 1113                     self.fp = io.open(file, filemode)
   1114                 except OSError:
   1115                     if filemode in modeDict:

FileNotFoundError: [Errno 2] No such file or directory: 'my_file.zip'
Rodrigo Vargas
  • 273
  • 3
  • 17
  • you shouldn't hard-code paths, see [no-such-file-or-directory-with-absolute-path](https://stackoverflow.com/questions/58383714/no-such-file-or-directory-with-absolute-path/58383966#58383966) – RMPR Oct 31 '19 at 22:43
  • 1
    Possible duplicate of ['No such file or directory' with absolute Path](https://stackoverflow.com/questions/58383714/no-such-file-or-directory-with-absolute-path) – RMPR Oct 31 '19 at 22:44
  • I don't see a variable named `name`. However, you're referencing it in your f-strings. – S3DEV Oct 31 '19 at 22:44

1 Answers1

0

This might be the key:

Revise this line:

dir_name = f"C:/my_path/zip/{name}"

To:

dir_name = "C:/my_path/zip"

Why?
Because os.listdir is looking in a directory named "C:/my_path/zip/{name}" but it doesn't exist as the variable name has not been declared. Thus the error below, as triggered on my machine (albeit Linux, hence the non-Windows type path):

FileNotFoundError: [Errno 2] No such file or directory: '/devmt/services/{name}' 

Then, apply this logic throughout the rest of your function and perhaps use os.path.join to stitch your path and filenames together.

S3DEV
  • 8,768
  • 3
  • 31
  • 42