Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python/zip:如果提供了文件的绝对路径,如何消除zip存档中的绝对路径?_Python_Zip_Absolute Path_Zipfile - Fatal编程技术网

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

python/zip:如果提供了文件的绝对路径,如何消除zip存档中的绝对路径?,python,zip,absolute-path,zipfile,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 = zipfil

我在两个不同的目录中有两个文件,一个是“/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()

打开我创建的zip文件后,我在其中有一个主文件夹,然后有两个子文件夹,第一个和第二个,然后是pdf文件。我不知道如何只包含两个pdf文件,而不是将完整路径压缩到zip存档中。我希望我把问题说清楚,请帮忙。谢谢。

我想可能有一个更优雅的解决方案,但这一个应该可以:

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()

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()

当您有一些空闲时间时,阅读的文档将很有帮助。

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

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

通过这种方式也可以创建大于2GB的归档文件

import os, zipfile
def zipdir(path, ziph):
    """zipper"""
    for root, _, files in os.walk(path):
        for file_found in files:
            abs_path = root+'/'+file_found
            ziph.write(abs_path, file_found)
zipf = zipfile.ZipFile(DEST_FILE.zip, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
zipdir(SOURCE_DIR, zipf)
zipf.close()

您可以使用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)

文档参考:

如果我想在zip文件中添加自定义文件夹名称,然后在该文件夹中显示最终文件,我该怎么办?如果您使用pathlib作为文件路径,可以使用first_path.name。