How to add lines to the beginning of a text file?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Apr 4 03:48:01 CEST 2009


On Sat, 04 Apr 2009 03:21:34 +0200, dean wrote:

> Hello,
> 
> As the subject says how would I go about adding the lines to the
> beginning of a text file? Thanks in advance.

I'm not aware of any operating system that allows you to insert data into 
the middle or beginning of a file, although I've heard rumours that some 
ancient operating systems (VAX?) may have.

To insert into a file, you have to do all the moving of data yourself. If 
the file is small enough to fit into memory, the easiest way is something 
like this:


# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("This is the new first line\n")
# write the original contents
f.write(text)
f.close()


But note that this isn't entirely safe, if your Python session crashes 
after opening the file the second time and before closing it again, you 
will lose data. For quick scripts, that's a minuscule risk, but for 
bigger applications, you should use a safer method, something like this:


# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open a different file for writing
f = open('filename~', 'w')
f.write("This is the new first line\n")
# write the original contents
f.write(text)
f.close()
# did everything work safely?
# if we get here, we're probably safe
os.rename('filename~', 'filename')


But note that even this is not entirely safe: it uses a predictable file 
name for the temporary file, which is generally a bad thing to do, it 
fails to flush data to disk, which means you're at the mercy of vagaries 
of the file system, and it doesn't do *any* error handling at all.

The standard library really needs a good "save data to file" solution.


-- 
Steven



More information about the Python-list mailing list