Python Forum
Help replacing word in Mutiple files. (SOLVED)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help replacing word in Mutiple files. (SOLVED)
#1
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)
Larz60+ write Mar-17-2023, 11:34 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode BBCode tags on future posts.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [solved] compressing files with python. SpongeB0B 1 609 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  python print all files which contain specific word in it mg24 5 1,188 Jan-27-2023, 11:20 AM
Last Post: snippsat
  delete all files which contains word sql_Table1 mg24 2 823 Sep-15-2022, 10:05 PM
Last Post: mg24
  Delete empty text files [SOLVED] AlphaInc 5 1,511 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE
  Sorting and Merging text-files [SOLVED] AlphaInc 10 4,755 Aug-20-2021, 05:42 PM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Replace String in multiple text-files [SOLVED] AlphaInc 5 7,963 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
Question (solved) open multiple libre office files in libre office lucky67 5 3,213 May-29-2021, 04:54 PM
Last Post: lucky67
  Searching for specific word in text files. JellyCreeper6 1 1,695 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  Complex word search multiple files Kristenl2784 0 1,556 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020