Edit contents of a zip file using Python?
Category:
Question ID: 109633
1
0

I have a collection of zip file from a weekly process I run, each one contains a few csv and json files. One of the csvs contains an engine type that needs to be changed. Is there a good way to make an automated process that will unzip these folders, edit a file in them, and zip them back up? Doing it manually will be a pain.

Marked as spam
Posted by (Questions: 9, Answers: 0)
Asked on June 19, 2020 7:22 pm
1015 views
Answers (1)
1
Private answer

Unfortunately there isn't necessarily an *easy* way to do this, but you definitely can do it.
You'll need to unzip the file, and then edit the contents in a new directory, zip it back up, and delete the temporary folder. You'll need the zipfile package for unzipping and the shutil package for packaging it back up.

from zipfile import ZipFile

import os

import shutil

foldername = basefilename(minus extensions)

with ZipFile(foldername + '.' + 'zip', 'r') as zipObj:
zipObj.extractall(foldername)

os.remove(foldername + '.zip')
#do whatever you want to do inside of the foldername directory here.
shutil.make_archive(foldername, 'zip', foldername)

#the temporary directory will still be around, so you'll need to delete all of the contents
#and then delete the actual folder.
for filename in os.listdir(filenamebase):
file_path = os.path.join(filenamebase, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
os.rmdir(filenamebase)

 

Marked as spam
Posted by (Questions: 0, Answers: 7)
Answered on June 19, 2020 7:56 pm
EyeOnTesting

Welcome back to "EyeOnTesting" brought to you by Orasi Software, Inc.

X
Scroll to Top