2

I have a simple code to zip files using zipfile module. I am able to zip some files but I get FileNotFound error for the others. I have checked if this is file size error but its not.

I can pack files with name like example file.py but when I have a file inside a directory like 'Analyze Files en-US_es-ES.xlsx' if fails.

It works when I change os.path.basename to os.path.join but I don't want to zip whole folder structure, I want to have flat structure in my zip.

Here is my code:

import os
import zipfile

path = input()

x=zipfile.ZipFile('new.zip', 'w')
for root, dir, files in os.walk(path):
    for eachFile in files:        
        x.write(os.path.basename(eachFile))
x.close()

Error looks like this:

Traceback (most recent call last):  
File "C:/Users/mypc/Desktop/Zip test.py", line 15, in <module>    
x.write(os.path.basename(eachFile))  
File "C:\Python34\lib\zipfile.py", line 1326, in write    
st = os.stat(filename)

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Analyze Files en-US_ar-SA.xlsx'*
Dharman
  • 30,962
  • 25
  • 85
  • 135
MaciejPL
  • 1,017
  • 2
  • 9
  • 16

1 Answers1

0

Simply change working directory to add file without original directory structure.

import os
import zipfile

path = input()

baseDir = os.getcwd()
with zipfile.ZipFile('new.zip', 'w') as z:
    for root, dir, files in os.walk(path):
        os.chdir(root)
        for eachFile in files:
            z.write(eachFile)
        os.chdir(baseDir)
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • thanks for help I have use path.basename instead because I dont want whole folder structure. – MaciejPL Apr 29 '15 at 08:22
  • @MaciejPL My bad, I copy-pasted it form my previous resoponse, where I misunderstood a problem. In your case `os.path.basename(eachFile)` would be equal to `eachFile` anyway. Please read [os.walk](https://docs.python.org/2/library/os.html#os.walk) docs. – Łukasz Rogalski Apr 29 '15 at 08:25
  • Thanks a lot I'm just confused about this dir changing parts. Could you please tell me what happens here. Really appriciate. – MaciejPL Apr 29 '15 at 09:01