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:
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.
