Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save carlynorama/4eb8249837b7120764fe to your computer and use it in GitHub Desktop.

Select an option

Save carlynorama/4eb8249837b7120764fe to your computer and use it in GitHub Desktop.
Update a file with new user input preserving first few lines as a header. Started from LPTHW Example 16
#http://learnpythonthehardway.org/book/ex16.html
#http://stackoverflow.com/questions/11584247/how-can-i-simplify-this-series-of-target-write-commands
#http://stackoverflow.com/questions/12790983/multiline-file-read-in-python
from sys import argv
script, filename = argv
title_lines = 2
print "We're going to all of %r but the first line." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'r+') #can be used only if file exists, a+ if you don't care.
title = [target.readline() for _ in range(title_lines)]
print "Truncating the file after title lines. Goodbye Garbage!"
target.truncate() #can pass this a character position to start/stop.
print "Now I'm going to ask you for three new lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write('{}\n{}\n{}\n'.format(line1, line2, line3))
#or
#target.write('\n'.join((line1,line2,line3))+'\n')
#or
#lines=(line1,line2,line3)
#target.write( '\n'.join(lines) + '\n')
print "Close the file."
target.close()
print '''Verify write:
--------------------------------------------------'''
target = open(filename, 'r')
print target.read()
print '''--------------------------------------------------
Close File'''
target.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment