Python Forum
Replace String in multiple text-files [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace String in multiple text-files [SOLVED]
#1
Hello everybody,

In a previous post I got help to find a string in a text-file, replace it with an increasing number and save it:

import re

target = "String"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

with open('input.txt', 'r') as file :
  filedata = file.read()

filedata = re.sub(re.escape(target), str_counter, filedata)

a_file = open("input.txt", "w")
text = filedata
print(text, file=a_file)
a_file.close()
Now I would like to expand this and do this for every txt-file inside a folder. Is there a way to go through the whole directory, open every file, replace the string with an increasing counter and then save it to the same file? With my posted code I am able to do this for the one specified file but I'd like to do this for every text-file.
Reply
#2
Modify your code above to become a function. Have the function take the name of the file and operate on it.

Then use glob.glob or Path.iterdir() (or os.scandir) to get all the files in a directory that you want. Loop over them and pass the filenames or filepaths to your function.
Reply
#3
(Aug-06-2021, 11:06 PM)bowlofred Wrote: Modify your code above to become a function. Have the function take the name of the file and operate on it.

Then use glob.glob or Path.iterdir() (or os.scandir) to get all the files in a directory that you want. Loop over them and pass the filenames or filepaths to your function.

Sorry to be so annoying but how do i do this exactly?
I'm pretty new to python
Reply
#4
As bowlofred already wrote, make a function and then call it for every txt file

import os

folder_path = "/path/to/folder/" # your path
            
for root, dirs, files in os.walk(folder_path, topdown = False):
   for name in files:
      if name.endswith(".txt"):
        file_name = os.path.join(root, name)
        print(file_name)
        #your_function(file_name) # call your function
Reply
#5
(Aug-07-2021, 11:45 AM)Axel_Erfurt Wrote: As bowlofred already wrote, make a function and then call it for every txt file

import os

folder_path = "/path/to/folder/" # your path
            
for root, dirs, files in os.walk(folder_path, topdown = False):
   for name in files:
      if name.endswith(".txt"):
        file_name = os.path.join(root, name)
        print(file_name)
        #your_function(file_name) # call your function

I tried to do it like this:

#!/usr/bin/env python3

import os
import re

folder_path = "/home/pi/Workspace/Case_02/" # your path

for root, dirs, files in os.walk(folder_path, topdown = False):
   for name in files:
      if name.endswith(".txt"):
        file_name = os.path.join(root, name)

target = "Format"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

with open(file_name, 'r') as file :
  filedata = file.read()

filedata = re.sub(re.escape(target), str_counter, filedata)

with open(file_name, 'w') as file:
    file.write(filedata)
I set an example with three different files (Out_01.txt, Out_02.txt, Out_03.txt) but the changes to my file were only written to Out_03.txt.

Edit: I just needed to set the right amount of spaces per indentation level.
Reply
#6
You did not create a function and your indentations are disastrous, try this

import os
import re
 
folder_path = "/home/pi/Workspace/Case_02/" # your path
target = "Format"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

def  do_it(file_name):
    with open(file_name, 'r') as file :
        filedata = file.read()
        print(filedata)
     
        filedata = re.sub(re.escape(target), str_counter, filedata)
    
        print(filedata)
     
        with open(file_name, 'w') as file:
            file.write(filedata)
            file.close()
        
for name in os.listdir(folder_path):
    if name.endswith(".txt"):
        file_name = os.path.join(folder_path, name)
        do_it(file_name)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [Solved] Getting python's default 'printed' byte-string as string ? MvGulik 8 135 Apr-06-2026, 09:16 AM
Last Post: Dustbunny
Question [SOLVED] Linefeed when writing "f" strings to text file? Winfried 5 858 Nov-04-2025, 11:51 AM
Last Post: buran
  replace or remove text from many text files Curbie 21 3,245 Jul-07-2025, 02:05 PM
Last Post: Curbie
Question [SOLVED] Open file, and insert space in string? Winfried 7 2,524 May-28-2025, 07:56 AM
Last Post: Winfried
Question [SOLVED] [Beautiful Soup] Replace tag.string from another file? Winfried 2 1,672 May-01-2025, 03:43 PM
Last Post: Winfried
Question [SOLVED] Right way to open files with different encodings? Winfried 3 10,291 Jan-18-2025, 02:19 PM
Last Post: Winfried
  [SOLVED] Sub string not found in string ? jehoshua 4 2,311 Dec-03-2024, 09:17 PM
Last Post: jehoshua
Question [SOLVED] How to replace characters in a string? Winfried 2 1,957 Sep-04-2024, 01:41 PM
Last Post: Winfried
  Trying to generating multiple json files using python script dzgn989 4 4,664 May-10-2024, 03:09 PM
Last Post: deanhystad
  [SOLVED] Loop through directories and files one level down? Winfried 3 4,379 Apr-28-2024, 02:31 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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