python/zip:如果提供文件的绝对路径,如何消除zip存档中的绝对路径?

Sha*_*ang 53 python zip absolute-path zipfile

我在两个不同的目录中有两个文件,一个是'/home/test/first/first.pdf',另一个是'/home/text/second/second.pdf'.我使用以下代码来压缩它们:

import zipfile, StringIO
buffer = StringIO.StringIO()
first_path = '/home/test/first/first.pdf'
second_path = '/home/text/second/second.pdf'
zip = zipfile.ZipFile(buffer, 'w')
zip.write(first_path)
zip.write(second_path)
zip.close()
Run Code Online (Sandbox Code Playgroud)

我打开我创建的zip文件后,我有一个home在它的文件夹,然后有两个子文件夹在里面,firstsecond,则PDF文件.我不知道如何只包含两个pdf文件,而不是将完整路径压缩到zip存档中.我希望我的问题清楚,请帮忙.谢谢.

Joã*_*nto 113

zipfile write()方法支持一个额外的参数(arcname),它是存储在zip文件中的存档名称,因此您只需要更改代码:

from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()
Run Code Online (Sandbox Code Playgroud)

当你有空闲时间阅读zipfile的文档将会有所帮助.


小智 10

我使用此函数来压缩目录而不包含绝对路径

import zipfile
import os 
def zipDir(dirPath, zipPath):
    zipf = zipfile.ZipFile(zipPath , mode='w')
    lenDirPath = len(dirPath)
    for root, _ , files in os.walk(dirPath):
        for file in files:
            filePath = os.path.join(root, file)
            zipf.write(filePath , filePath[lenDirPath :] )
    zipf.close()
#end zipDir
Run Code Online (Sandbox Code Playgroud)


shx*_*hx2 5

我怀疑可能会有一个更优雅的解决方案,但是这个应该可以工作:

def add_zip_flat(zip, filename):
    dir, base_filename = os.path.split(filename)
    os.chdir(dir)
    zip.write(base_filename)

zip = zipfile.ZipFile(buffer, 'w')
add_zip_flat(zip, first_path)
add_zip_flat(zip, second_path)
zip.close()
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用以下参数覆盖存档中的文件名arcname

with zipfile.ZipFile(file="sample.zip", mode="w", compression=zipfile.ZIP_DEFLATED) as out_zip:
for f in Path.home().glob("**/*.txt"):
    out_zip.write(f, arcname=f.name)
Run Code Online (Sandbox Code Playgroud)

文档参考:https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.write