0
def replace_line(file_name, line_num, find, replace):
    lines = open(file_name, 'r').readlines()
    print("This : ", find, " will be replaced for this: ", replace)
    lines[line_num].replace(find, replace)
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

replace_line('text.txt', 3, 'num="200.00"\n', 'num="7.00"\n')

I am trying to replace a specific "str" in a specific line in a text file, however, it does not change anything. Im using Python 3.9

1 Answers1

0

You need to assign the output to a variable. Strings are immutable in python, so str.replace() returns a new string.

def replace_line(file_name, line_num, find, replace):
    lines = open(file_name, 'r').readlines()
    print("This : ", find, " will be replaced for this: ", replace)
    lines = lines[line_num].replace(find, replace) ### < Fixed this line
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

replace_line('text.txt', 3, 'num="200.00"\n', 'num="7.00"\n')
blackbrandt
  • 2,010
  • 1
  • 15
  • 32
  • Thanks a lot for your reply. Now I understand what you did there, but now my file only has that replaced line on it and erased the other lines. I wanted to edit only this line but keep the rest of it. Is there a way I could do it? – Victor M Aug 12 '21 at 16:38
  • That is a different question, and needs to be asked in its own question. Take what you have, walk through line by line to figure out what it's doing, and the answer should become apparent. – blackbrandt Aug 12 '21 at 16:40