Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip list of files python

Tags:

python

csv

zip

I have created some csv files in my code and I would like to zip them as one folder to be sent by e-mail. I already have the e-mail function but the problem is to zip. I tried to use this: here I am not extracting or find the files in a directory. I am creating the program the csv files and making a list of it. My list of files is like this:

lista_files = [12.csv,13.csv,14.csv]

It seems to be easy for developers but as a beginning it is hard. I would really appreciate if someone can help me.

like image 819
may Avatar asked Dec 21 '17 08:12

may


People also ask

How do I zip multiple files in Python?

Create a zip archive from multiple files in PythonCreate a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.

What does zip (*) do in Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.


1 Answers

I believe you're looking for the zipfile library. And given that you're looking at a list of filenames, I'd just iterate using a for loop. If you have directories listed as well, you could use os.walk.

import zipfile

lista_files = ["12.csv","13.csv","14.csv"]
with zipfile.ZipFile('out.zip', 'w') as zipMe:        
    for file in lista_files:
        zipMe.write(file, compress_type=zipfile.ZIP_DEFLATED)
like image 139
Neil Avatar answered Sep 20 '22 14:09

Neil