Replace a number inside of a text file

Viewed 47

I have a file.txt

some text
another text
text with the number to be replaced bla123
another text
etc

I know that the number I'm looking for is on line 3. I also know this is the only number in the line. For example, here, I want to replace "123" with "3333". I don't know what the number will be nor it's length before searching for it.

file.txt should look like this:

some text
another text
text with the number to be replaced bla3333
another text
etc
2 Answers

you can use re library to do so

https://docs.python.org/3/library/re.html

re.sub will replace any specific regular expression pattern with whatever you want. If you use '\d+' as your pattern, it'll replace any number with what you want. Since there is only one number, this should do the trick

So if your line is s_line :

import re
number = 3333
new_string = re.sub('\d+', str(number), s_line)

So to complete the global exercice, here is what the code should look like :

import re
number = 3333

my_file = r"path/to/file"
file_content = []
with open(my_file, 'r') as f_in:
    line_number = 1
    line = f_in.readline()
    while line:
        if line_number == 3:
            line = re.sub('\d+', str(number), line)
        file_content.append(line)
        line_number += 1
        line = f_in.readline()

with open(my_file, 'w') as f_out:
    f_out.write("".join(file_content))

you can solve this in 3 easy steps:

  1. read the file and keep the lines in memory
  2. replace any number on line 3 (mind that arrays are 0-indexed in python) with a replacement string
  3. write the output to your file

This uses the regex module re

import re

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

replacement = '3333'
lines[2] = re.sub('\d+', replacement, lines[2])

with open('myfile.txt', 'w') as f:
    f.writelines(lines)
Related