Python Forum

Full Version: Help replacing word in Mutiple files. (SOLVED)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm learning Python and I need to replace this word "VELIVE9" with "VELIVE" in multiple files. I'm stuck.
I have tried different things but I can't get it to work.

My code is below. When i run the code below I get this output.
How can I loop thru each file and replace the words. Thank you!

Output:
C:\visual\xxx\VMFG Visual.ini C:\visual\xxx\VMFG Visual.ini
import os

for folderName,subFolders,fileNames in os.walk(r'C:\visual'):
    for each_file in fileNames:
        if "Visual.ini" == each_file:
            print(folderName, each_file)
______
Bing Chat - resolved the issue for me - Below is the working example

import os

start_dir = r'C:\Users\home\Documents\visual'

search_text = 'VELIVE99'
replace_text = 'VELIVE'

for dirpath, dirnames, filenames in os.walk(start_dir):
    for filename in filenames:
        with open(os.path.join(dirpath, filename), 'r') as file:
            file_contents = file.read()

        new_file_contents = file_contents.replace(search_text, replace_text)
        with open(os.path.join(dirpath, filename), 'w') as file:
            file.write(new_file_contents)