python/zip:如果提供了文件的绝对路径,如何消除 zip 存档中的绝对路径? [英] python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided?

查看:46
本文介绍了python/zip:如果提供了文件的绝对路径,如何消除 zip 存档中的绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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

如果您有空闲时间阅读 zipfile 的文档会很有帮助.

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

这篇关于python/zip:如果提供了文件的绝对路径,如何消除 zip 存档中的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆