将文件添加到现有的 zipfile
Adding file to existing zipfile
我正在使用 python 的 zipfile
模块。
将 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.write(os.path.basename('/home/user/a/b/c/1.txt'))
并得到一个文件不存在的错误,尽管它确实存在。
你非常接近:
zip.write(path_to_file, os.path.basename(path_to_file))
应该能帮到你。
说明:zip.write
函数接受第二个参数(arcname),它是要存储在 zip 存档中的文件名,请参阅文档以获取 zipfile 更多详细信息。
os.path.basename()
为您删除路径中的目录,以便文件将以其名称存储在存档中。
请注意,如果您只 zip.write(os.path.basename(path_to_file))
,它将在当前目录中查找该文件(如错误所述)不存在的文件。
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)
我正在使用 python 的 zipfile
模块。
将 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.write(os.path.basename('/home/user/a/b/c/1.txt'))
并得到一个文件不存在的错误,尽管它确实存在。
你非常接近:
zip.write(path_to_file, os.path.basename(path_to_file))
应该能帮到你。
说明:zip.write
函数接受第二个参数(arcname),它是要存储在 zip 存档中的文件名,请参阅文档以获取 zipfile 更多详细信息。
os.path.basename()
为您删除路径中的目录,以便文件将以其名称存储在存档中。
请注意,如果您只 zip.write(os.path.basename(path_to_file))
,它将在当前目录中查找该文件(如错误所述)不存在的文件。
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)