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]
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 =

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

a_file = open("input.txt", "w")
text = filedata
print(text, file=a_file)
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.

Messages In This Thread
Replace String in multiple text-files [SOLVED] - by AlphaInc - Aug-06-2021, 10:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to generating multiple json files using python script dzgn989 4 500 May-10-2024, 03:09 PM
Last Post: deanhystad
  [SOLVED] Loop through directories and files one level down? Winfried 3 546 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
  replace text in a txt cartonics 19 2,850 Jan-30-2024, 06:58 AM
Last Post: Athi
  python convert multiple files to multiple lists MCL169 6 1,894 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Replace a text/word in docx file using Python Devan 4 4,910 Oct-17-2023, 06:03 PM
Last Post: Devan
  Need to replace a string with a file (HTML file) tester_V 1 988 Aug-30-2023, 03:42 AM
Last Post: Larz60+
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,457 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  splitting file into multiple files by searching for string AlphaInc 2 1,180 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
Question [solved] compressing files with python. SpongeB0B 1 801 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  Replace string in a nested Dictianory. SpongeB0B 2 1,426 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B

Forum Jump:

User Panel Messages

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