Python - 使用 ZipFile 创建错误的 zip 文件

Python - Creating bad zip files with ZipFile

我的脚本从位于文本文件中的 URL 下载文件,将它们临时保存到给定位置,然后将它们添加到同一目录中的现有 zip 文件中。文件正在成功下载,添加到 zip 文件时没有出现错误,但由于某些原因,大多数生成的 zip 文件无法被 OS 打开,当我 z.printdir()在它们上面,它们不包含所有预期的文件。

相关代码:

for root, dirs, files in 
os.walk(os.path.join(downloadsdir,dir_dictionary['content']), False):
if "artifacts" in root:
    solution_name = root.split('/')[-2]
    with open(os.path.join(root,'non-local-files.txt')) as file:
        for line in file:
            if "string" in line:
                print('\tDownloading ' + urllib.unquote(urllib.unquote(line.rstrip())))
                file_name = urllib.unquote(urllib.unquote(line.rstrip())).split('/')[-1]
                r = requests.get(urllib.unquote(urllib.unquote(line.rstrip())))
                with open(os.path.join(root,file_name), 'wb') as temp_file:
                    temp_file.write(r.content)
                z = zipfile.ZipFile(os.path.join(root, solution_name + '.zip'), 'a')
                z.write(os.path.join(root,file_name), os.path.join('Dropoff', file_name))

我想我的问题是:我是不是在代码中做错了什么,还是我必须查看添加到 zip 文件中的实际文件?据我所知,这些文件都是 OS 可读的,并且看起来很正常。有点不知所措。

for root, dirs, files in 
os.walk(os.path.join(downloadsdir,dir_dictionary['content']), False):
if "artifacts" in root:
    solution_name = root.split('/')[-2]
    with open(os.path.join(root,'non-local-files.txt')) as file:
        for line in file:
            if "string" in line:
                print('\tDownloading ' + urllib.unquote(urllib.unquote(line.rstrip())))
                file_name = urllib.unquote(urllib.unquote(line.rstrip())).split('/')[-1]
                r = requests.get(urllib.unquote(urllib.unquote(line.rstrip())))
                with open(os.path.join(root,file_name), 'wb') as temp_file:
                    temp_file.write(r.content)
                z = zipfile.ZipFile(os.path.join(root, solution_name + '.zip'), 'a')
                try:
                    z.write(os.path.join(root,file_name), os.path.join('Dropoff', file_name))
                finally:
                    z.close()

PS: https://docs.python.org/2/library/zipfile.html

备注

存档名称应该相对于存档根目录,也就是说,它们不应该以路径分隔符开头。

这里没有针对 ZIP 文件的官方文件名编码。如果您有 unicode 文件名,则必须在将它们传递给 write() 之前将它们转换为所需编码的字节字符串。 WinZip 将所有文件名解释为 CP437 编码,也称为 DOS Latin。