Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a new line of text at top of a file?

I'm developing a simple program which makes a Python script executable, and I'm working in the part which adds the interpreter path (#! /usr/bin/python). I tried to do it, but instead of adding a new line, it replaces the current and removes part of the next line. What I'm doing wrong?

I uploaded the source code to Ubuntu Pastebin: http://pastebin.ubuntu.com/1032683/ The wrong code is between lines 28 and 31:

wfile = open(file, 'r+')
if wfile.readline() != "#! /usr/bin/python\n":
    wfile.seek(0)
    wfile.write("#! /usr/bin/python\n")

Using Python 2.7.2 with an iPad 2 (Python for iOS), also using 2.5.1 in the same iPad (Cydia port) for testing.

like image 505
Xerz Avatar asked Oct 17 '25 01:10

Xerz


1 Answers

You can't do what you're trying to do. Seeking to the beginning of a file and doing a write will overwrite from that position, not append.

The only way to add a line in the middle (or beginning) of a file is to write out a new file with the data inserted where you want it to.

like image 145
Joe Avatar answered Oct 18 '25 14:10

Joe