Home > OS >  how to replace strings in a file using a loop counter
how to replace strings in a file using a loop counter

Time:03-23

I have a file named: my_file.txt

And inside this my_file.txt, I have some strings such as:

name1 name1 name1 name1 name1 name1 name1 name1 name1 name1

And I need to do a bulk loop counter on that 1 to 10 to look like:

name1 name2 name3 name4 name5 name6 name7 name8 name9 name10

So far I only have this, which I found here:

https://www.geeksforgeeks.org/how-to-search-and-replace-text-in-a-file-in-python

But that just swaps one string for another. And I need to use the counter.

search_text = "dummy"

replace_text = "replaced"

with open(r'my_file.txt', 'r') as file:

    data = file.read()
    data = data.replace(search_text, replace_text)

with open(r'my_file.txt', 'w') as file:

    file.write(data)

print("Text replaced")

CodePudding user response:

You can simply do iterative replace and replacing one occurence at each time.

Work with chunks to improve performance in case the string is very very big


with open(r'my_file.txt', 'r') as file:
    data = file.read()
    
search_text = "dummy"
replace_text = "replaced"
n_replaced = 0
index = 0


chunks = []
while True:
    index = data.find(search_text)
    if index == -1:
        break
    replace_text_counter = f"{replace_text}{n_replaced}"
    chunks.append(data[:index])
    data = data[index:].replace(search_text, replace_text_counter, 1)
    n_replaced  = 1
chunks.append(data)

with open(r'my_file.txt', 'w') as file:
    file.write("".join(chunks))

print("Text replaced")

CodePudding user response:

To ignore the read and write file and lines in your case. I give a code just deal with string line which you gave name1 name1 name1 name1 name1 name1 name1 name1 name1 name1:

string = "name1 name1 name1 name1 name1 name1 name1 name1 name1 name1"
li = string.split()
i=0
for i<len(li):
  li[i]=li[i].replace("1",i 1)
return ' '.join(li)
  • Related