Search code examples
pythonfilereplacefile-handlingfile-manipulation

How can I over-write a string in a file using python?


So I have a text file (called 'Numbers') which looks like this:

1 - 2 - 3 - 8 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  

I want to replace the number 8 in the first line with a number 4. How do I do this?
So far I've got the following:

File = open('Numbers.txt','r+')  
for line in File:
  Row = line.split(' - ')
  FourthValue = Row[3]
  NewFourthValue = '4'
  NewLine = line.replace(FourthValue,NewFourthValue)
  File.write(NewLine)
  break
File.close()

Then, it appends the new correct line onto the end of the file like this:

1 - 2 - 3 - 8 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 61 - 2 - 3 - 4 - 5 - 6

What can I do to make this new line replace the first line?


Solution

  • After reading the first line you need to "rewind" the file so you can overwrite the first line.

    with open(fname, 'r+') as f:
        row = f.readline()
        row = row.replace('8', '4')
        f.seek(0)
        f.write(row)
    

    Be careful when doing this though, because if the new data isn't exactly the same size as the old data you will mess up the following lines. Generally, it's much simpler & safer to create a new file, copying the (possibly modified) lines from one to the other, but it is nice to know this technique if you ever have to process huge files.

    FWIW, my answer here handles the more general case of in-place modification of the data at an arbitrary position in the file.