Python zipfile整个路径在文件中 [英] Python zipfile whole path is in file
问题描述
我使用的是此处的代码 从目录制作 zip 文件.我给函数一个从 GUI 到文件夹的绝对路径.目前,假设路径是 c:\users......,zip 文件夹结构是 users...... .
I'm using the code from here to make a zip file from a directory. I give the function an absolute path to a folder from a GUI. Currently, say the path is c:\users......, the zip folder structure is users...... .
我怎样才能删除绝对路径位并只使用用于 zip 文件的路径的结束文件夹?我知道结果是正确的,因为我描述的是 os.walk 的结果,但我想去掉绝对路径.
How can I remove the absolute path bits and just have the end folder of the path being used for the zip file? I understand that the result is right, because what I'm describing is the result from os.walk but I want to strip out the absolute path.
def zipdir(path, zip):
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
推荐答案
这样做:
def zipdir(path, zip):
path = os.path.abspath(path)
for root, dirs, files in os.walk(path):
dest_dir = root.replace(os.path.dirname(path), '', 1)
for file in files:
zip.write(os.path.join(root, file), arcname=os.path.join(dest_dir, file))
这会将给定的 path
转换为绝对路径,其目录名称用于删除 root
中的前导路径组件.
This converts the given path
to an absolute path, the directory name of which is used to remove the leading path component in root
.
这篇关于Python zipfile整个路径在文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!