我有一些代码可以将文件夹中的特定扩展文件写入 zip 文件。虽然我继续遇到错误。我从几个不同的来源提取了这段代码。我能得到一些帮助吗?
ext = [".shp", ".shx", ".prj", ".cpg", ".dbf"]
# compress shapefile and name it the ortho name
for folder, subfolder, files in os.walk('D:/combined_shape'):
for file in files:
if file.endswith(tuple(ext)):
zipfile.ZipFile('D:/combined_shape/' + 'compiled' + '/.zip', 'w').write(os.path.join(folder, file),
os.path.relpath(os.path.join(folder, file),
'D:/combined_shape/'), compress_type = zipfile.ZIP_DEFLATED)
Traceback (most recent call last):
File "D:/PycharmProjects/Augmentation/merge_shp.py", line 30, in <module>
zipfile.ZipFile('D:/combined_shape/' + 'compiled' + '/.zip', 'w').write(os.path.join(folder, file),
File "D:\PyCharmEnvironments\lib\zipfile.py", line 1240, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'D:/combined_shape/compiled/.zip'
答案 0 :(得分:0)
“找不到文件或目录”错误是因为 zip 文件的名称中包含 /.zip
。应删除 /
。
在存档中只获取一个文件的问题是在打开 w
时使用了 ZipFile
模式。正如文档中所述:
'w' 截断并写入新文件
因此,对于您要添加的每个文件,首先要删除之前添加的所有文件。
在循环之前打开文件一次,然后将每个文件添加到其中。
with zipfile.ZipFile('D:/combined_shape/compiled.zip', 'w') as z:
for folder, subfolder, files in os.walk('D:/combined_shape'):
for file in files:
if file.endswith(tuple(ext)):
z.write(os.path.join(folder, file),
os.path.relpath(os.path.join(folder, file),
'D:/combined_shape/'),
compress_type = zipfile.ZIP_DEFLATED)