IO in python 3 not writing/reading


I am copying an example from a book with a piece of code to write and read a file that has already been created (using utf-8). The thing is that the code I have doesn’t print anything when I run it:

#encoding = utf-8
import io 

f ="abc.txt", "wt", encoding = "utf-8")
texto = u"Writing with díférént chars"

text ="abc.txt", encoding = "utf-8").read()
Asked By: eduardo0



You are missing parens in the call to close:


Adding that then it prints for me in both python2 and python3.

Writing to a buffered io (the default using may causes writes to be deferred — especially when writing small amounts of data (less than the default buffer size). Since the file is never closed, the buffer is never flushed to disk causing subsequent reads to see the file as truncated (the initial state when the file gets opened for writing).

I’d strongly suggest using the contextmanager protocol instead (as you won’t even have to think about closing files):

# encoding: utf-8
import io 

with"abc.txt", "wt", encoding="utf-8") as f:
    texto = u"Writing with díférént chars"

with"abc.txt", encoding="utf-8") as f:
Answered By: Anthony Sottile
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.