Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: zipfile.ZipFile No such file or directory

There is folder path:

P:\\2018\\Archive\\

There are many zipfiles I want to create programmatically, but am starting with test. I will name this test zip file "CO_007_II.zip" and will attempt to create in above location:

import zipfile as zp

with zp.ZipFile("P:\\2018\\Archive\\CO_007_II.zip",'w') as myzip:
    myzip.write(r"P:\2018\CO_007_II")

But I get error!

...

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'P:\\2018\\Archive\\CO_007_II.zip'

Is this not method for creating new zipfile? I know file does not exist. Is why I am using 'w' mode, no?

This is documentation:

https://docs.python.org/3/library/zipfile.html

It says:

'w' to truncate and write a new file

Example on documentation page:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

code worked two days ago to create new zip file but did not add folder. Today nothing works! Why not? All paths valid. How do I create new zip file with python and add folders to it?

like image 251
geoJshaun Avatar asked May 09 '18 23:05

geoJshaun


3 Answers

I also encountered a similar issue and came here looking for answers. Since this was the top hit, I'll add what I discovered.

The answer provided by @metatoaster didn't work for me, when stepping through the code I found that the path returned true to isdir.

In my case, the path length exceeded the Windows max path length (260 chars) which was causing it to fail despite the folder path being valid.

Hope that helps someone else down the line!

like image 180
Dawson Young Avatar answered Oct 17 '22 00:10

Dawson Young


The only way this could be reproduced was to create a zipfile in a directory that does NOT exist yet. The only way to be sure (you cannot trust a file manager; only way to verify is to check from within the program itself) is to assign the desired path of the new zip file to a variable (e.g. path), and then call isdir(dirname(path)). For example:

from os.path import isdir
from os.path import dirname

target = "P:\\2018\\Archive\\CO_007_II.zip"
if not isdir(dirname(target)):
    print('cannot create zipfile because target does not exists')
else:
    # create the zipfile
like image 3
metatoaster Avatar answered Oct 17 '22 00:10

metatoaster


I had the same issue. It was the long path. I solved by adding this //?/C at the beginning of the path

path = r"//?/C:\Users\Camilo\Proyectos"

like image 2
camilogutierrez Avatar answered Oct 17 '22 01:10

camilogutierrez