Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend a line to an existing file in Python

Tags:

python

prepend

I need to add a single line to the first line of a text file and it looks like the only options available to me are more lines of code than I would expect from python. Something like this:

f = open('filename','r') temp = f.read() f.close()  f = open('filename', 'w') f.write("#testfirstline")  f.write(temp) f.close() 

Is there no easier way? Additionally, I see this two-handle example more often than opening a single handle for reading and writing ('r+') - why is that?

like image 941
Nick Avatar asked Dec 15 '10 19:12

Nick


People also ask

How do you append to an existing line in Python?

You can't append to a line, however, you can overwrite part of the line. If you leave a bunch of blanks at the end of the line so that you can record up to e.g., 5 scores and update the line in place.


1 Answers

Python makes a lot of things easy and contains libraries and wrappers for a lot of common operations, but the goal is not to hide fundamental truths.

The fundamental truth you are encountering here is that you generally can't prepend data to an existing flat structure without rewriting the entire structure. This is true regardless of language.

There are ways to save a filehandle or make your code less readable, many of which are provided in other answers, but none change the fundamental operation: You must read in the existing file, then write out the data you want to prepend, followed by the existing data you read in.

By all means save yourself the filehandle, but don't go looking to pack this operation into as few lines of code as possible. In fact, never go looking for the fewest lines of code -- that's obfuscation, not programming.

like image 67
Nicholas Knight Avatar answered Sep 25 '22 17:09

Nicholas Knight