everyone. When I am trying to print out the content of the file, I found that if I don't close the file after writing it, I can't read the content and print it out, can anyone explain to me what's happening? Also, is there any alternative way to accomplish that?
wf = open('text.txt','w')
wf.write("HI\nThis is your testing txt file\n!!!")
rf = open('text.txt', 'r')
print(rf.read())
wf.close()
rf.close()
File operations, in all programming languages, are usually buffered by default. That means that the actual writing does not actually happen when you write
, but when a buffer flushing occurs. You can force this in several ways (like .flush()
), but in this case, you probably want to close the file before opening it again - this is the safest way as opening a file twice could create some problems.
wf = open('text.txt','w')
wf.write("HI\nThis is your testing txt file\n!!!")
wf.close()
rf = open('text.txt', 'r')
print(rf.read())
rf.close()
Coming to Python, a more idomatic way to handle files is to use the with
keyword which will handle closing automatically:
with open('text.txt','w') as wf:
wf.write("HI\nThis is your testing txt file\n!!!")
with open('text.txt') as rf:
print(rf.read())
I recommend to read or write files as follows:
#!/usr/bin/env python3.6
from pathlib import Path
p = Path('text.txt')
p.write_text("HI\nThis is your testing txt file\n!!!")
print(p.read_text())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.