将文件添加到现有 zip 文件

2024-04-28

我正在使用 python 的zipfile module.
zip 文件位于以下路径:
/home/user/a/b/c/test.zip
并在下面创建另一个文件/home/user/a/b/c/1.txt我想将此文件添加到现有的 zip 中,我这样做了:

zip = zipfile.ZipFile('/home/user/a/b/c/test.zip','a')
zip.write('/home/user/a/b/c/1.txt')
zip.close()`

并且在解压缩文件时所有子文件夹都出现在路径中,如何仅输入没有路径子文件夹的zip文件?

我也尝试过:zip.write(os.path.basename('/home/user/a/b/c/1.txt'))并收到一个错误,表明文件不存在,尽管它确实存在。


import zipfile

# Open a zip file at the given filepath. If it doesn't exist, create one.
# If the directory does not exist, it fails with FileNotFoundError
filepath = '/home/user/a/b/c/test.zip'
with zipfile.ZipFile(filepath, 'a') as zipf:
    # Add a file located at the source_path to the destination within the zip
    # file. It will overwrite existing files if the names collide, but it
    # will give a warning
    source_path = '/home/user/a/b/c/1.txt'
    destination = 'foobar.txt'
    zipf.write(source_path, destination)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将文件添加到现有 zip 文件 的相关文章

随机推荐