python file read() displaying empty line -
i following series of tutorials (http://learnpythonthehardway.org/book/ex16.html ) online , stuck. have looked everywhere answer cannot seem o find solution. apologise if silly question , obvious total beginner.
the script below works fine except 1 mistake. .read () command on line 29 returns empty when script run.
if tell me why , how fix happy.
kind regards. :)
from sys import argv script, filename = argv print "we going erase %r" % filename print "if not want hit ctrl c ( ^c )." print "if want hit return." raw_input ("?") print "opening file....." target = open (filename, "r+") print "truncating file. goodbye!" target.truncate () print "now going ask 3 lines" line1 = raw_input ("line 1:") line2 = raw_input ("line 2:") line3 = raw_input ("line 3:") print "now, im going write 3 lines %s file:" % filename target.write ("%s\n%s\n%s" % (line1, line2, line3)) print "now going show contents of file:" print target.read() print "and close." target.close()
the file cursor has been moved after writes. natural consequence of writing. if want read wrote, need reset file cursor beginning of file:
target.seek(0)
...subsequent reads have access text you've put in file.
Comments
Post a Comment