【发布时间】:2016-10-17 08:33:47
【问题描述】:
我正在尝试使用 os.walk() 压缩一个文件夹以及每个包含的子文件夹和文件,但我无法删除根文件夹的文件夹路径 - 这意味着我想在打开 zip 文件时删除 D:\\Users\\Username\\Desktop ,而是直接打开到根文件夹。
我一直在尝试使用 os.path.basename() 和 zipfile 的 arcname 参数,但似乎无法正确使用:
def backupToZip(folder):
import zipfile, os
folder = os.path.abspath(folder) # make sure folder is absolute
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
# Add the current folder to the ZIP file.
backupZip.write(foldername)
# Add all the files in this folder to the ZIP file.
for filename in filenames:
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
backupToZip('Sample Folder')
【问题讨论】:
-
您能否发布您希望压缩存档结构的外观?您发布的代码有点令人困惑,因为它是递归的,没有对函数的初始调用。
-
@hobenkr:很抱歉有任何混淆 - 我希望 zip 文件夹结构为
Sample Folder\Subfolders and Files\Subfolders and Files而不是D:\\Users\\Username\\Desktop\\Sample Folder\\Subfolders and Files\\Subfolders and Files