0

Below is the code for

  • unzipping a folder containing text fies

  • find and replace a string within those file

  • zip it back.

import shutil
import zipfile
import sys
from pathlib import Path
        
class ZipProcessor:
    def __init__(self, zipname):
        self.zipname = zipname
        self.temp_directory = Path("unzipped-{}".format(zipname[:-4]))

    def process_zip(self):
        self.unzip_files()
        self.process_files()
        self.zip_files()

    def unzip_files(self):
        self.temp_directory.mkdir()
        with zipfile.ZipFile(self.zipname) as zip: 
            zip.extractall(str(self.temp_directory))

    def zip_files(self):
        with zipfile.ZipFile(self.zipname, 'w') as file:
            for filename in self.temp_directory.iterdir():
                print(filename)                            # second
                file.write(str(filename), filename.name)
        shutil.rmtree(str(self.temp_directory))


class ZipReplace(ZipProcessor):
    def __init__(self, filename, search_string,replace_string):
        super().__init__(filename)
        self.search_string = search_string
        self.replace_string = replace_string
    
    def process_files(self):
        '''perform a search and replace on all files in the
        temporary directory'''
        for filename in self.temp_directory.iterdir():
            with filename.open() as file:
                contents = file.read()
            contents = contents.replace(self.search_string, self.replace_string)
            with filename.open("w") as file:
                file.write(contents)

if __name__ == "__main__":
    ZipReplace(*sys.argv[1:4]).process_zip()
        

I run the code with the python3 EX5_zip.py replace3.zip 'code' 'program'

The error is receive is IsADirectoryError: [Errno 21] Is a directory: 'unzipped-replace3/replace'

My doubt is regarding the directory replace under the temp_directory path. How did it get created with that name? I doubt if its from the previous run of the script [ I had given zipfile as ```replace.zip``]. if that's the case how do I remove it from the memory ?

I used the following link to remove memory but the it remains.

Salih
  • 391
  • 1
  • 13

1 Answers1

0

Either:

  • there was already a replace subfolder in unzipped-replace3
  • or there is a replace directory inside your replace3.zip zip file so that folder was created by extractall

So when you try to open the Path("replace") given by iterdir with filename.open, it fails. You should first test if filename is a directory or not with filename.is_dir().

benselme
  • 3,157
  • 3
  • 17
  • 22