I'm currently working my way through Learning Python the Hard Way and I've got a little bit stuck on a modification I wanted to make on exercise 16.
So, this is my code:
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 do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename,'w+')
#Print contents ## WHY WONT THIS WORK??
print "This was inside your file %r:" % filename
target.seek(0)
print target.read()
This is where my problem is. The print
function above does not print the file, rather just gives a blank line. The rest of the code follows below and as you will see there is a second print
that works fine.
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: ")
print "I'm going to write these to the file."
target.write(("\n%s\n%s\n%s\n") % (line1, line2, line3))
#This print does work
target.seek(0)
print target.read()
print "And finally, we close it."
target.close()
What am I doing wrong here?