28564

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.

Answer1:

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.

Answer2:

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)

Answer3:

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,

Recommend

  • Swift 4: Firebase Timestamp
  • Error when exporting with pydub - how to install mp3 codecs for pydub?
  • How to prevent user from entering zero as an input?
  • Twitter json API foreign characters
  • Using BOOST_FOREACH with a constant intrusive list
  • JAR file: Could not find main class
  • How to read data from socket connection - android
  • Unable to run app-client that is accessing an EJB on GlassFish v3
  • C# where to add a method
  • Valums Ajax file Upload handle the up. file?
  • How can I allow tags through rails 4 sanitize?
  • vi mode to emacs mode while on R
  • Removing event listeners on automatically created multiple elements
  • How do you SELECT several columns with one distinct column
  • Save website uploads in a subdomain
  • What is ./.local/share/Trash (Unix) [closed]
  • Building Qt project for C++11 standard
  • User messaging system
  • Python pickle not one-to-one: different pickles give same object
  • Reading a file into a multidimensional array
  • Redux Form - Not able to type anything in input
  • Abort upload large uploads after reading headers
  • Meteor: Do Something On Email Verification Confirmation
  • Counter field in MS Access, how to generate?
  • Where to put my custom functions in Wordpress?
  • Javascript + PHP Encryption with pidCrypt
  • Websockets service method fails during R startup
  • RestKit - RKRequestDelegate does not exist
  • Traverse Array and Display in markup
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • WPF Applying a trigger on binding failure
  • Acquiring multiple attributes from .xml file in c#
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • Understanding cpu registers
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Turn off referential integrity in Derby? is it possible?
  • How can I remove ASP.NET Designer.cs files?
  • JaxB to read class hierarchy
  • java string with new operator and a literal