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 argvscript, filename = argvprint The name of the script is: %r % script# open txt file and display on screentext1 = open(filename, 'r')print text1.read()text1.close()# ask user to overwrite the fileprint 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 linetext2 = 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 filetext3 = open(filename, 'r')print text3.read()text3.close()
Reading and Writing in same script
python;python 2.7;file;console;io