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()
3
  • 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: stackoverflow.com/questions/3167494/… Commented May 29, 2018 at 10:11
  • Use with open(.., so you don't have to worry about closing file. Commented May 29, 2018 at 10:12
  • Possible duplicate of Python 2.7 : Write to file instantly Commented May 29, 2018 at 10:12

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

Comments

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.