Simplex
Simplex

Reputation: 35

Appending string data to top of text file in Python?

I have a little code at the bottom of my program that is supposed to add a text header to the beginning of my text file. The data writes to the bottom of the file. I was reading in 'Learn Python The Hard Way' that .seek(0) would put the insertion point at the beginning, which is at the location of 0 bytes. However, I must be implementing the function incorrectly.

print 'Now, I will write a header to the original file to display copyright.'

append_copy = open(filename, "a+")
append_copy.seek(0)
append_copy.write("Copyright -- Ryan -- 2014\n")
append_copy.close()

print 'File closed and data written!'

Upvotes: 1

Views: 4500

Answers (2)

merlin2011
merlin2011

Reputation: 75555

The other answer was absolutely correct that this cannot be done directly, but you do not need to create a temporary file to do what you want.

You can clobber files with Python, if you open them with the flag w, so you do not need to create a temporary file, assuming your original file was small enough to hold in memory.

filename = "Foo.txt";
print 'Now, I will write a header to the original file to display copyright.'

append_copy = open(filename, "r")
original_text = append_copy.read()
append_copy.close()

append_copy = open(filename, "w")
append_copy.write("Copyright -- Ryan -- 2014\n")
append_copy.write(original_text)
append_copy.close()

print 'File closed and data written!'

The clobbering is documented here.

'w' for only writing (an existing file with the same name will be erased)

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

What you're doing won't work, but what you want can't be done.

Opening a file in append mode means that writes are always appended at the end of the file. That's what "append" means, so that should not entirely be a surprise.

But no filesystem allows inserting bytes at an arbitrary point regardless. You will need to create a new file, write the desired bytes to it, copy the contents of the old file, delete or rename the old file, and then rename the new file.

Upvotes: 2

Related Questions