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
#2
It seems to me that the first argument of FileInput is a sequence of files. You could perhaps pass the tuple (filename,) instead of filename. Also you could perhaps do a single call with FileInput(glob('*LIC'), ...)
Reply
#3
One can use os.scandir() to get list of files in current directory:

files = [entry for entry in os.scandir() if entry.name.endswith('.LIC')] 
Then iterate over this list to open files, read content, make replacement and write back (warning: this is untested code):

for file in files:
    with open(file, 'r+') as f:
        content = f.read().replace('abcd', 'efgh')
        f.write(content)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
(Oct-14-2019, 07:39 AM)perfringo Wrote: One can use os.scandir() to get list of files in current directory:

files = [entry for entry in os.scandir() if entry.name.endswith('.LIC')] 
Then iterate over this list to open files, read content, make replacement and write back (warning: this is untested code):

for file in files:
    with open(file, 'r+') as f:
        content = f.read().replace('abcd', 'efgh')
        f.write(content)

I tried this logic for single file and it is not replacing the content, it is just appending with older content
Reply
#5
Yeah, different I/O operations needed, this should work:

for file in files:
    with open(file, 'r') as f:
        content = f.read().replace('abcd', 'efgh')
    with open(file, 'w') as f:
        f.write(content)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
Malt Wrote:I tried this logic for single file and it is not replacing the content, it is just appending with older content
Or you could perhaps add a f.seek(0) before the write, and perhaps f.truncate() after the write.
Reply
#7
Can use in_place which make it easier the read/write to same place in one go.
import os
import in_place

for files in os.scandir('.'):
    if files.name.endswith('.LIC'):
        with in_place.InPlace(files) as f:
            text = f.read().replace('abcd', 'efgh')
            f.write(text)
Reply
#8
(Oct-14-2019, 10:42 AM)snippsat Wrote: Can use in_place which make it easier the read/write to same place in one go.
import os
import in_place

for files in os.scandir('.'):
    if files.name.endswith('.LIC'):
        with in_place.InPlace(files) as f:
            text = f.read().replace('abcd', 'efgh')
            f.write(text)

Idea Angel
Reply
#9
This is one of those cases where I wouldn't use Python. In my mind, this is a job for the shell and friends (at least on Unix; if you're on Windows, I can't help you).

Consider two files with some contents in the current directory:

Output:
$ cat first-file foo bar baz $ cat second-file baz qux bar foo bar qux
I can use find to, well, find the files in the current directory, loop over them in the shell (Bash in my case), using sed to, say, replace "bar" with "foo":

Output:
$ for file in $(find . -type f); do sed -i.bak 's/bar/foo/g' $file; done $ cat first-file foo foo baz $ cat second-file baz qux foo foo foo qux
The Grymoire has lots of useful tutorials on these sorts of tools.
Reply


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 522 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Need to replace a string with a file (HTML file) tester_V 1 751 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Rename files in a folder named using windows explorer hitoxman 3 729 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  splitting file into multiple files by searching for string AlphaInc 2 875 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Rename all files in a folder hitoxman 9 1,472 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  Replace string in a nested Dictianory. SpongeB0B 2 1,183 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,559 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  How to loop through all excel files and sheets in folder jadelola 1 4,437 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,203 Nov-28-2022, 12:41 PM
Last Post: snippsat
  python gzip all files from a folder mg24 3 3,952 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