4

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.

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
Xerz
  • 314
  • 1
  • 4
  • 15
  • You can post code directly into questions here. If it's too big, then it's probably too much code for the question. – Joe Jun 09 '12 at 20:43
  • possible duplicate of [append line to beginning of a file](http://stackoverflow.com/questions/5914627/append-line-to-beginning-of-a-file) – Wooble Jun 09 '12 at 20:52
  • possible duplicate of [Prepend a line to an existing file in Python](http://stackoverflow.com/questions/4454298/prepend-a-line-to-an-existing-file-in-python) – jfs Jun 09 '12 at 20:58

3 Answers3

6

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.

Joe
  • 41,484
  • 20
  • 104
  • 125
  • 2
    @espectalll123: Joe is absolutely correct. Any solution will require you to `read()` the entire contents of the file, insert a line at the beginning, and then `write()` the entire contents back into the file. – Joel Cornett Jun 09 '12 at 20:49
  • In that case, I will rewrite the program. Thanks. – Xerz Jun 09 '12 at 20:50
3

Joe is correct in that you have to can't just "insert" lines at the beginning of the file. Here is a solution for you, however:

with open(my_python_script, "r+") as f:
    first_line = f.readline()
    if first_line != "#! /usr/bin/python\n":
        lines = f.readlines()
        f.seek(0)
        f.write("#! /usr/bin/python\n")
        f.write(first_line)
        f.writelines(lines)         
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
2

To add/replace the first line in each file given at a command line:

#!/usr/bin/env python
import fileinput

shebang = "#! /usr/bin/python\n"
for line in fileinput.input(inplace=1):
    if fileinput.isfirstline() and line != shebang:
       print shebang,
       if not line.startswith("#!"): 
          print line,
    else:
       print line,
jfs
  • 399,953
  • 195
  • 994
  • 1,670