Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

zipfile

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.

like image 367
Mark K Avatar asked Aug 28 '14 08:08

Mark K


People also ask

How do I zip a group of files in Python?

To zip multiple files in Python, use the zipfile. ZipFile() method. Iterate all the files that need to be zipped and use the write() method to write the final zipped file.

How do I get a list of files in a ZIP file?

In Python's zipfile module, ZipFile class provides a member function to get the names of all files in it i.e. It returns a list of file names in Zip archive. Create a ZipFile object by opening the 'sampleDir. zip' in read mode and get the list of files in it using ZipFile.


2 Answers

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.

like image 90
Martijn Pieters Avatar answered Sep 18 '22 14:09

Martijn Pieters


original answered Sep 2 '14 at 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.

ZipFile.write(a, "C:\\" + os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)
like image 36
Mark K Avatar answered Sep 16 '22 14:09

Mark K