Reputation: 75
I have a folder named "DataFiles", there are files like: 2016-04-26.csv, 2016-04-27.csv,2016-05-12.csv... I want to zip the csv files that belongs to same months... for that i trying the below code:
import datetime
import os
import zipfile
yearP= None
monthP = None
for csvfiles in os.listdir("DataFiles"):
csvname, formata = csvfiles.split(".")
year, month, date = csvname.split("-")
if (yearP==year and monthP == month):
zip = zipfile.ZipFile('%s.zip' %monthyear , 'a')
zip.write('%s.csv' %csvname )
yearP= year
monthP = month
else:
zip = zipfile.ZipFile('%s.zip' %monthyear , 'a')
zip.write('%s.csv' %csvname )
yearP= year
monthP = month
but because of not in the sorted order it returns unusual results. I want to zip the according to the month and named the zipped file as the respective monthyear.
Upvotes: 2
Views: 144
Reputation: 16945
Since your files are in YYYY-MM-DD
format, you can lexicographically sort them.
Replace
for csvfiles in os.listdir("DataFiles"):
with
for csvfiles in sorted(os.listdir("DataFiles")):
This may become less tractable with a huge number of .csv files and you may need to rethink your algorithm, but for a small number, it's fine.
Upvotes: 1