在Python3.6中编写没有绝对路径的zipfile
我正在尝试使用Python的zipfile模块编写一个zip文件,该模块从某个子文件夹开始,但仍然保持该子文件夹的树结构。例如,如果我传递C:\Users\User1\OneDrive\Documents,zip文件将包含从Documents开始的所有内容,所有文档的子文件夹都保存在Documents中。我有以下代码:在Python3.6中编写没有绝对路径的zipfile,python,zipfile,Python,Zipfile,我正在尝试使用Python的zipfile模块编写一个zip文件,该模块从某个子文件夹开始,但仍然保持该子文件夹的树结构。例如,如果我传递C:\Users\User1\OneDrive\Documents,zip文件将包含从Documents开始的所有内容,所有文档的子文件夹都保存在Documents中。我有以下代码: import zipfile import os import datetime def backup(src, dest): """Backup files from
import zipfile
import os
import datetime
def backup(src, dest):
"""Backup files from src to dest."""
base = os.path.basename(src)
now = datetime.datetime.now()
newFile = f'{base}_{now.month}-{now.day}-{now.year}.zip'
# Set the current working directory.
os.chdir(dest)
if os.path.exists(newFile):
os.unlink(newFile)
newFile = f'{base}_{now.month}-{now.day}-{now.year}_OVERWRITE.zip'
# Write the zipfile and walk the source directory tree.
with zipfile.ZipFile(newFile, 'w') as zip:
for folder, _ , files in os.walk(src):
print(f'Working in folder {os.path.basename(folder)}')
for file in files:
zip.write(os.path.join(folder, file),
arcname=os.path.join(
folder[len(os.path.dirname(folder)) + 1:], file),
compress_type=zipfile.ZIP_DEFLATED)
print(f'\n---------- Backup of {base} to {dest} successful! ----------\n')
我知道我必须为zipfile.write使用arcname参数,但我不知道如何让它保持原始目录的树结构。现在的代码将每个子文件夹写入zip文件的第一级(如果有意义的话)。我读过几篇文章,建议我使用os.path.relname来切掉根,但我似乎不知道如何正确地进行。我也知道这篇文章看起来和其他关于堆栈溢出的文章相似。我读过其他的帖子,不知道如何解决这个问题。请告诉我 arcname参数将为要添加的文件设置zip文件中的确切路径。问题在于,为arcname构建路径时,使用了错误的值来获取要删除的前缀的长度。具体而言:
arcname=os.path.join(folder[len(os.path.dirname(folder)) + 1:], file)
应改为:
arcname=os.path.join(folder[len(src):], file)
工作得很有魅力!谢谢你的帮助。