Python Forum
Replace string in many files in a folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace string in many files in a folder
#1
This code changes a string in 1 text file in python
s = open("sample.txt").read()
s = s.replace('abcd', 'efgh')
f = open("mount.txt", 'w')
f.write(s)
f.close()
How do I change a single string ex: from abcd to efgh in 100's of text files under a single directory.

Thanks

I also tried this.It runs without errors but changes nothing in the text files.
I ran the code under the directory under which the files are stored.
import glob,os,fileinput
from glob import glob
for filename in glob('*.LIC'):
    with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace('abcd', 'efgh'),  end='')
Reply


Messages In This Thread
Replace string in many files in a folder - by metro17 - Oct-14-2019, 06:01 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 606 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Need to replace a string with a file (HTML file) tester_V 1 796 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Rename files in a folder named using windows explorer hitoxman 3 785 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 935 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Rename all files in a folder hitoxman 9 1,556 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  Replace string in a nested Dictianory. SpongeB0B 2 1,247 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,629 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  How to loop through all excel files and sheets in folder jadelola 1 4,574 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  Printing a raw string with a folder separator at the end, duplicates the separator krulah 5 1,252 Nov-28-2022, 12:41 PM
Last Post: snippsat
  python gzip all files from a folder mg24 3 4,126 Oct-28-2022, 03:59 PM
Last Post: mg24

Forum Jump:

User Panel Messages

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