0

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()
  • See this question, what you're asking python to do is to flush the buffer that wf is holding in memory to the file so that rf can read it from there: https://stackoverflow.com/questions/3167494/how-often-does-python-flush-to-a-file – Jonas May 29 '18 at 10:11
  • Use `with open(..`, so you don't have to worry about closing file. – Austin May 29 '18 at 10:12
  • Possible duplicate of [Python 2.7 : Write to file instantly](https://stackoverflow.com/questions/18984092/python-2-7-write-to-file-instantly) – Jonas May 29 '18 at 10:12

2 Answers2

2

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())
kabanus
  • 24,623
  • 6
  • 41
  • 74
0

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())
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30