I’m running this from eclipse, the file name I’m working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the “print txt.read()” doesn’t seem to do anything (prints a blank line), see the output after the code:
filename = raw_input("What's the file name we'll be working with?")
print "we're going to erase %s" % filename
print "opening the file"
target = open(filename, 'w')
print "erasing the file"
target.truncate()
print "give me 3 lines to replace file contents:"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "writing lines to file"
target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)
#file read
txt = open(filename)
print "here are the contents of the %s file:" % filename
print txt.read()
target.close()
Output:
What’s the file name we’ll be working with?ex16_text.txt
we’re going to erase ex16_text.txt
opening the file
erasing the file
give me 3 lines to replace file contents:
line 1: three
line 2: two
line 3: one
writing lines to file
here are the contents of the ex16_text.txt file:
1 Answer