jeudi 7 juillet 2016

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?

Aucun commentaire:

Enregistrer un commentaire