I'm following an exercise in the book Learn Python the Hard Way. In the following code example, I'm opening, truncating and then writing to a file. When I try to use print target.read() without another repetitive target = open(filename) statement, I get an error message stating that it cannot list the contents of the script I'm currently working on because it's not open.
I'm wondering why do I need the repetitive target = open(filename) statement if I opened the file previously using the target = open(filename, 'w') statement.
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you don't want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
target.write(line1, "\n", line2, "\n", line3)
target = open(filename)
print target.read()
print "And finally, we close it."
target.close()