我的脚本是从位于文本文件中的URL下载文件,将它们临时保存到给定位置,然后将它们添加到同一目录中已存在的zip文件中。文件正在成功下载,添加到zip文件时不会出现任何错误,但由于某些原因,操作系统无法打开大多数生成的zip文件,当我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文件中的实际文件?这些文件都是操作系统可读的,据我所知,看起来很正常。有点不知道如何继续。
答案 0 :(得分:1)
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。