I just finished working through Exercise 16 of Learn Python The Hard Way. To further study, I wanted to create a script that will read and display a file's contents on screen, and then have the user re-write the file with three lines.
Can my code be written in a much cleaner, pythonic way?
from sys import argv script, filename = argv print "The name of the script is: %r" % script # open txt file and display on screen text1 = open(filename, 'r') print text1.read() text1.close() # ask user to overwrite the file print "To overwrite this file, hit <enter>." print "Otherwise, CTRL-C to escape." raw_input('> ') # open the txt file again; overwrite it with different data # have user input new data for each line text2 = open(filename, 'w') print "Write three lines to the file." line1 = raw_input('line 1: ') line2 = raw_input('line 2: ') line3 = raw_input('line 3: ') text2.write('\n'.join([line1, line2, line3, ''])) text2.close() # read and display reconstructed file text3 = open(filename, 'r') print text3.read() text3.close()