【发布时间】:2020-01-27 14:57:35
【问题描述】:
所以到目前为止,我的程序能够成功添加和压缩与test.py 位于同一目录中的文件,但在同一目录中还有一个名为location 的文件夹,其中包含其他文件,比如citynames.txt 什么发生是当我做一个简单的 zip.write (else 块中使用的逻辑)location 被添加到 zip 文件中,但是它是空的,因为某种原因它里面不包含citynames.txt 请帮我添加文件夹本身不知何故?
import os
import zipfile
import shutil
dir_path = os.path.dirname(os.path.realpath(__file__)) #holds the directory where script is located
os.chdir(dir_path) #Changes to directory where script is located
fp=os.listdir(dir_path) #file pointer
directory_size=len(os.listdir(dir_path))
zip1=zipfile.ZipFile('Archive.zip','w')
for i in range(directory_size) :
if fp[i]=='test.py':
break
if fp[i]=='location':
#Some code needs to be added here to write all the contents of folder "location" into
"Archive.zip"
else:
zip1.write(fp[i],compress_type=zipfile.ZIP_DEFLATED)
print("Process completed")
编辑
假设 location 有更多的子文件夹如何压缩其中的文件?
【问题讨论】:
-
你有代码,做一个备份,这样你就可以恢复,然后尝试运行它。
-
是的,我做到了.. 谢谢!而且它仍然没有给我
locations子文件夹或其内容整天都在尝试:S
标签: python python-2.7 zipfile