Reputation: 11
I am currently on Excercise 16 in Learn Python the Hard Way and i'm having a problem with my code where it will write onto the file, but my final print command does not print the contents of the file onto the console. On my command line, it just comes up with a couple of lines of blank space.From my understand "r+"opens it in read and write mode, but the computer cannot to read it. Could someone tell me whats wrong with it please? Any help would be appreciated :)
from sys import argv
script, file = argv
print "The name of the file is %s" % file
filename = open(file,"r+")
print "First we must write something in it "
print "Do you want to continue?Press CTRL-C if not."
raw_input()
print "Type the first line of the text"
line1 = raw_input(">")+"\n"
print "Type the second line of text"
line2 = raw_input(">")+"\n"
print "Type the third line of text"
line3 = raw_input(">")+"\n"
sum_line = line1 + line2 + line3
print "Now I will write it to the file"
filename.write(sum_line)
print "The file now says:"
#This line here does not print the contents of the file
print filename.read()
filename.close()
Upvotes: 1
Views: 54
Reputation: 53535
Since you wrote into the file, the offset after writing will point to the end of the file. At that point, if you want to read the file from the beginning you'll have to close it and re-open it.
By the way, since Python 2.5 the with
statement is supported and recommended to use, for example:
with open('yourfile', 'r') as f:
for line in f:
...
Using with
will take care of closing the file for you!
Upvotes: 1
Reputation: 15953
Without having to close then reopen the file you can add filename.seek(0)
which will take it back to the top of the file.
filename = open('text.txt',"r+")
print(filename.read())
lin = input()
filename.write(lin)
filename.seek(0) # take it back to top, 0 can be changed to whatever line you want
print(filename.read())
filename.close()
Upvotes: 0
Reputation: 11144
As included in the first answer, after writing the offset will be pointing to the end of the file. However, you don't need to close the file and reopen it. Rather do this before reading it :
filename.seek(0)
That will reset the offset at the start of the file.
Then simply read it.
filename.read()
Upvotes: 2