Using Python to add a list of files into a zip file

↘锁芯ラ 提交于 2019-12-05 16:17:51

问题


I want to write a script to add all the ‘.py’ files into a zip file.

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.


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/25544475/using-python-to-add-a-list-of-files-into-a-zip-file

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