Search code examples
pythonstringfiledirectory

Python change strings line by line in all files within a directory


So I have some files located in directory. Some of the files contain paths like this and some are empty: C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c

What would be the best way to cut it just by counting backslashes from the end: So in this case we need to cut everything what is after 4th backslash when counting backward:

Folder1\Folder2\Folder3\Module.c

I need some function that will go through all files and do this on each line of a file.

Current code which do not work for some reason is:

directory = os.listdir(//path_to_dir//)
for file in directory:
    with open (file) as f:
        for s in f:
            print('\\'.join(s.split('\\')[-4:])) 

Solution

  • I would try something like this:

    from pathlib import Path
    
    def change(s):
        return '\\'.join(s.split('\\')[-4:])
    
    folder = Path.cwd() / "folder" # here is your folder with files
    files = folder.glob("*")
    
    for f in files:
        with open(f, "r") as file:
            content = file.read()
    
        lines = content.split('\n')
        new_lines = []
    
        for line in lines:
            new_lines.append(change(line))
    
        with open(f, "w") as file:
            file.write("\n".join(new_lines))
    

    It look for all files in the subfolder folder, does replacing on every line of every file and saves the files.