简体   繁体   English

在没有文件夹结构的python中压缩文件

[英]zipping files in python without folder structure

I want to create a zip file of some files somewhere on the disk in python.我想在 python 的磁盘上的某处创建一些文件的 zip 文件。 I successfully got the path to the folder and each file name so I did:我成功获得了文件夹的路径和每个文件名,所以我做了:

with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip:
                for file in filesToZip:
                    zip.write(self.folderPath + file)

Everything works fine, but the zipfile that is output contains the entire folder structure leading up to the files.一切正常,但输出的 zipfile 包含导致文件的整个文件夹结构。 Is there a way to only zip the files and not the folders with it?有没有办法只压缩文件而不压缩文件夹?

From the documentation :文档

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None) ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed).将名为filename的文件写入存档,为其指定存档名称arcname (默认情况下,这将与 filename 相同,但没有驱动器号并删除前导路径分隔符)。

So, just specify an explicit arcname :因此,只需指定一个显式的arcname

with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip:
                for file in filesToZip:
                    zip.write(self.folderPath + file, arcname=file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM