Search code examples
pythonfilefor-loopzip

Python - Problems with zipfiles


my zip file (folder) with 20 text files in it is saved locally. I have the directory of that. What I want to do:

  1. I want to upzip the folder, search through with a loop, to get the right text file (for ex. "testcase1"), which should be edited.
  2. Open this text file and add new line for example "hello world" -> save and close
  3. Next I want do zip this folder again and save it locally in a special directory
  4. return the path of the new zip file (folder)

Solution

  • This worked for me:

     import zipfile
                def update_log(self, input_dir, output_dir):
                '''
                function to update the log files
                '''
        
                with ZipFile(input_dir, 'r') as zip:
                    # printing all the contents of the zip file
                    zip.printdir()
                    # extracting all the files
                    self.logger.info("Extracting all the files now...")
                    os.chdir(output_dir)
                    zip.extractall()
                    print('Done!')
    
                #for loop, opening file, edit and close
                for key in testcase_dict:
                    log_file = open('{}.txt'.format(key), 'a')
                    log_file.write('hello world')
                    log_file.close()
    
                # calling function to get all file paths in the directory
                file_paths = self.get_all_file_paths()
                # printing the list of all files to be zipped
                for file_name in file_paths:
                    print(file_name)
                    # writing files to a zipfile
                with ZipFile('log-test.zip', 'w') as zip:
                    # writing each file one by one
                    for file in file_paths:
                        zip.write(file)
        
                print("All files zipped successfully")
                return None
        
        
            def get_all_file_paths(self):
                # initializing empty file paths list
                file_paths = []
        
                # crawling through directory and subdirectories
                for root, directories, files in os.walk("home/test"):
                    for filename in files:
                        # join the two strings in order to form the full filepath.
                        filepath = os.path.join(root, filename)
                        file_paths.append(filepath)
        
                        # returning all file paths
                self.logger.info(file_paths)
                return file_paths