python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided?

大城市里の小女人 提交于 2019-11-26 10:41:02

问题


I have two files in two different directories, one is \'/home/test/first/first.pdf\', the other is \'/home/text/second/second.pdf\'. I use following code to compress them:

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

After I open the zip file that I created, I have a home folder in it, then there are two sub-folders in it, first and second, then the pdf files. I don\'t know how to include only two pdf files instead of having full path zipped into the zip archive. I hope I make my question clear, please help. Thanks.


回答1:


The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:

from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()

When you have some spare time reading the documentation for zipfile will be helpful.




回答2:


I use this function to zip a directory without include absolute path

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



回答3:


I suspect there might be a more elegant solution, but this one should work:

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



回答4:


Can be done that way also (this allow for creating archives >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()


来源:https://stackoverflow.com/questions/16091904/python-zip-how-to-eliminate-absolute-path-in-zip-archive-if-absolute-paths-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!