Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify the last line of a file?

Tags:

python

file

The last line of my file is:

29-dez,40,

How can I modify that line so that it reads:

29-Dez,40,90,100,50

Note: I don't want to write a new line. I want to take the same line and put new values after 29-Dez,40,

I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.

like image 659
UcanDoIt Avatar asked Feb 03 '23 12:02

UcanDoIt


1 Answers

Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.

On the other hand maybe your file is really huge - multiple GBs at least. In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line.

So perhaps:

f = open("foo.file", "wb")
f.seek(-len(os.linesep), os.SEEK_END) 
f.write("new text at end of last line" + os.linesep)
f.close() 

(Modulo line endings on different platforms)

like image 50
Douglas Leeder Avatar answered Feb 06 '23 15:02

Douglas Leeder