[英]Using Python to add a list of files into a zip file
I want to write a script to add all the '.py' files into a zip file.我想编写一个脚本来将所有 '.py' 文件添加到一个 zip 文件中。
Here is what I have:这是我所拥有的:
import zipfile
import os
working_folder = 'C:\\Python27\\'
files = os.listdir(working_folder)
files_py = []
for f in files:
if f[-2:] == 'py':
fff = working_folder + f
files_py.append(fff)
ZipFile = zipfile.ZipFile("zip testing.zip", "w" )
for a in files_py:
ZipFile.write(a, zipfile.ZIP_DEFLATED)
However it gives an error:但是它给出了一个错误:
Traceback (most recent call last):
File "C:\Python27\working.py", line 19, in <module>
ZipFile.write(str(a), zipfile.ZIP_DEFLATED)
File "C:\Python27\lib\zipfile.py", line 1121, in write
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
File "C:\Python27\lib\ntpath.py", line 125, in splitdrive
if p[1:2] == ':':
TypeError: 'int' object has no attribute '__getitem__'
so seems the file names given is not correct.所以似乎给出的文件名不正确。
You need to pass in the compression type as a keyword argument:您需要将压缩类型作为关键字参数传入:
ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)
Without the keyword argument, you are giving ZipFile.write()
an integer arcname
argument instead, and that is causing the error you see as the arcname
is being normalised.如果没有关键字参数,您ZipFile.write()
一个整数arcname
参数,这会导致您看到的错误,因为arcname
正在被规范化。
original answered Sep 2 '14 at 3:52原回答 2014 年 9 月 2 日 3:52
according to the guidance above, the final is: (just putting them together in case it could be useful)根据上面的指导,最终是:(只是将它们放在一起以防万一)
import zipfile
import os
working_folder = 'C:\\Python27\\'
files = os.listdir(working_folder)
files_py = []
for f in files:
if f.endswith('py'):
fff = os.path.join(working_folder, f)
files_py.append(fff)
ZipFile = zipfile.ZipFile("zip testing3.zip", "w" )
for a in files_py:
ZipFile.write(os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)
ZipFile.close()
added in Mar 2020 enlightened by @jinzy at zip file and avoid directory structure , the last line of above changed to below to avoid file structures in the zip file.于 2020 年 3 月由 @jinzy 在zip file and avoid directory structure启发下添加,上面的最后一行更改为下面以避免 zip 文件中的文件结构。
ZipFile.write(a, "C:\\" + os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.