'How to read files and folders recursively in python? Then rename the sub-directory and file name by finding a particular string in the file

My goal is to read all the folders inside the root directory and then read the sub-directories and then read the .txt files inside that particular sub-directory. Now after reading the file I wanna rename the files inside it and once all the files are renamed and then I wanna rename the sub-directory as well.

This is the content present in the .txt files:

pp-2454177|Anil, Marry Hector|67000|104R updated as of 9.17 signed byabc.pdf
pp-2454178|John, Hector|77000|104R tooly part time plan2026.doc

pp-2454177 is the original sub-directory name and 67000 is the original filename.

Now the 67000.txt file should be renamed by whatever is there after 67000 in the .txt file excluding the pipe symbol, we have to do this similarly for all files respectively. So after renaming the filename will be: 104R updated as of 9.17 signed byabc.pdf

Once all the files are renamed, now I wanna rename the sub-directory to whatever is there after pp-2454177. So after renaming the sub-directory name will be: Anil, Marry Hector

I tried and I was able to read the files in each sub-directory but I'm not understanding how to check that filename inside the .txt files and rename them.

import os
from pathlib import Path

rootdir = 'E:\Huzaifa\Folder Rename Python Program'

# Read files inside sub-directories and print the text inside each file respectively
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith(".txt"):
            file_path = f"{subdir}\{file}"
            # print(file_path)
            with open(file_path, 'r') as f:
                # print(f.read())
                file_name = Path(file_path).stem
                file_name_with_extension = file_name + ".txt"

                all_files = [file_name]
                for lines in f:
                    print(lines)
                    

This is my folder structure: folder-structure

May I please get a detailed explanation of the problem that I described?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source