Reputation: 85
This program simply takes a file, deletes it, allows the user to input two lines which are put into the blank file, then prints the file.
But why do I have to close the file object and reopen it before it displays the newly added lines?
(Notice the file isn't printed in this version of the code. But if you remove the #'s it will perform correctly)
from sys import argv
sript, filename = argv
print "We will be buliding a new file from an %s" % filename
print "If you don't want to do this, hit CTRL_C"
print "If you do, hit and other key"
raw_input(">>>")
print "Oppening the file..."
file_ob = open(filename, "r+")
file_ob.truncate()
print "Now we will rewrite this file with the following line"
line1 = raw_input("The fist line will be :")
line2 = raw_input("The second line will be:")
print "Now we're put them into the file"
file_ob.write("\n\t>>>" + line1 + "\n\n\t>>>" + line2)
print "And now we will see what is in the file we just made"
print file_ob.read()
file_ob.close()
print "And now we will see what is in the file we just made"
#file_ob = open(filename, "r+")
#print file_ob.read()
#file_ob.close()
Upvotes: 1
Views: 103
Reputation: 155684
File objects are buffered by default; unless you write enough data to fill the buffer, it won't write to the file until the file is flushed or closed (which implicitly flushes). This is done to avoid making lots of (expensive) system calls for small writes. You can always force a flush directly by calling fileobj.flush()
.
Some other notes: if the goal is to open for read/write and truncate the file, just open with mode 'w+'
, not 'r+'
followed by truncate()
. Second, use with
statements, so you don't accidentally fail to close the file (by omitting the close
, or bypassing it thanks to an exception being thrown). Example:
with open(filename, "w+") as file_ob:
# Don't need to truncate thanks to w+
# Do writes/reads, with explicit flushes if needed
# When block exited by any means, file is flushed and closed automatically
Upvotes: 5