我想编写一个脚本,将所有'.py'文件添加到zip文件中。
这就是我所拥有的:
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)
但是它会出错:
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__'
所以给出的文件名似乎不正确。
答案 0 :(得分:12)
您需要将压缩类型作为关键字参数传递:
ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)
如果没有关键字参数,您将给ZipFile.write()
一个整数arcname
参数,这会导致您看到arcname
正常化时出现的错误。
答案 1 :(得分:5)
根据上述指导,决赛是: (只是将它们放在一起以防它可能有用)
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)