-2

My txt.files are saved in zipped-subfolders as follows:

  • mainfolder.zip
  • mainfolder/folder1 (folder 1 is no zip-file)
  • mainfolder/folder1/subfolder11.zip
  • mainfolder/folder1/subfolder12.zip
  • mainfolder/folder2 (folder 2 is no zip file)
  • mainfolder/folder1/subfolder21.zip
  • mainfolder/folder1/subfolder22.zip

I want to loop over all the text files in subfolders of the mainfolder. Is there an easy way to do it?

Mk88
  • 1
  • 1

1 Answers1

0

I hope to help.

If the script is not in the folder with the folder to be searched, replace os.getcwd() with the path to the folder.

import os
import logging
from pathlib import Path
from shutil import unpack_archive

# unzipping all zipped folders
zip_files = Path(os.getcwd()).rglob("*.zip")
while True:
    try:
        path = next(zip_files)
    except StopIteration:
        break
    except PermissionError:
        logging.exception("permission error")
    else:
         extract_dir = path.with_name(path.stem)
         unpack_archive(str(path), str(extract_dir), 'zip')

# finding and dealing with a .txt file
for root, dirs, files in os.walk(os.getcwd()):
  for f in files:
    if os.path.splitext(f)[1].lower() == ".txt":
        with open(os.path.join(root, f)) as fi:
            lines = fi.readlines()
            print("File: ",os.path.join(root, f),"\ncontent: ", lines)
            # all what you want do with file...

Nice day :)