因此,到目前为止,我的程序能够成功地添加和压缩与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")
编辑
假设位置有更多的子文件夹,那么如何压缩其中的文件呢
您需要将位置中的每个文件单独添加到
zip1
。将其添加到相应的
if
-分支:无法将目录添加到zip存档的原因是
zip1.write
不是递归的(它不会添加目录树下较远的文件,只添加您明确要求它添加的文件)。您需要使用os.walk
遍历所有子目录并分别添加每个文件:注意,上面的代码是由Mark Byers根据this答案改编的
清单[Python 3.Docs]: zipfile - Work with ZIP archives
代码中的(主要)问题是您将继续误认为是中断。这样,当遇到test.py时,它后面的所有项目都将被忽略,因为break退出循环
这里有一个变量,它使用[Python 3.Docs]: glob.iglob(pathname, *, recursive=False)递归到子目录中,并在存档中添加文件
code00.py:
输出:
相关问题 更多 >
编程相关推荐