Help replacing word in Mutiple files. (SOLVED) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help replacing word in Mutiple files. (SOLVED) (/thread-39624.html) |
Help replacing word in Mutiple files. (SOLVED) - mm309d - Mar-21-2023 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!
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) |