Unable to unzip archive created using zipfile (Python)

I'm having problems with the archive that I created using the zipfile in Python. I repeat all the files in the directory and write them to the archive. When I try to retrieve them after this, I get an exception related to the path separator.

the_path= "C:\\path\\to\\folder"
zipped= cStringIO.StringIO()
zf = zipfile.ZipFile(zipped_cache, "w", zipfile.ZIP_DEFLATED)
for dirname, subdirs, files in os.walk(the_path) :
    for filename in files:
        zf.write(os.path.join(dirname, filename), os.path.join(dirname[1+len(the_path):], filename))
zf.extractall("C:\\destination\\path")
zf.close()
zipped_cache.close()

Here's an exception:

zipfile.BadZipfile: the file name in the directory "env \ index" and the header "env / index" are different.

Update: I replaced the string buffer cStringIO.StringIO()with a temporary file ( tempfile.mkstemp("temp.zip")), and now it works. Something happens there when the zipfile module writes to a buffer that corrupts the archive, but is not sure what the problem is.

, / / , "r" / "w" "rb" / "wb". Linux, Windows - . . >

+3
4

: http://www.penzilla.net/tutorials/python/scripting.

, . , , , zip . 2 . os.walk .

def zippy(path, archive):
    paths = os.listdir(path)
    for p in paths:
        p = os.path.join(path, p) # Make the path relative
        if os.path.isdir(p): # Recursive case
            zippy(p, archive)
        else:
            archive.write(p) # Write the file to the zipfile
    return

def zipit(path, archname):
    # Create a ZipFile Object primed to write
    archive = ZipFile(archname, "w", ZIP_DEFLATED) # "a" to append, "r" to read
    # Recurse or not, depending on what path is
    if os.path.isdir(path):
        zippy(path, archive)
    else:
        archive.write(path)
    archive.close()
    return "Compression of \""+path+"\" was successful!"
+2

r , , . escape-.

:

#!/bin/env python    
print(r"C:\destination\path")
print(r"C:\path\to\folder")
print("C:\destination\path")
print("C:\path\to\folder")

:

C:\destination\path
C:\path\to\folder
C:\destination\path
C:\path o
         older

, \t \f tab formfeed .

, (.. open("C:/path/to/folder"), .

, (.. open("C:\\path\\to\\folder")).

IMO, r.


: , , . , zipfile - , , , , . (. 6839).

+4

You need to avoid backslashes on your paths.

Try changing the following:

  • the_path= "C:\path\to\folder"before the_path = "C:\\path\\to\\folder"and
  • zf.extractall("C:\destination\path")- zf.extractall("C:\\destination\\path").
+1
source

You can use slashes as path separators, even on Windows. I suggest trying when you create a zip file.

+1
source

All Articles