IO in python 3 not writing/reading
Question:
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 = io.open("abc.txt", "wt", encoding = "utf-8")
texto = u"Writing with díférént chars"
f.write(texto)
f.close
text = io.open("abc.txt", encoding = "utf-8").read()
print(text)
Answers:
You are missing parens in the call to close
:
f.close()
Adding that then it prints for me in both python2 and python3.
Writing to a buffered io (the default using io.open
) 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 io.open("abc.txt", "wt", encoding="utf-8") as f:
texto = u"Writing with díférént chars"
f.write(texto)
with io.open("abc.txt", encoding="utf-8") as f:
print(f.read())
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 = io.open("abc.txt", "wt", encoding = "utf-8")
texto = u"Writing with díférént chars"
f.write(texto)
f.close
text = io.open("abc.txt", encoding = "utf-8").read()
print(text)
You are missing parens in the call to close
:
f.close()
Adding that then it prints for me in both python2 and python3.
Writing to a buffered io (the default using io.open
) 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 io.open("abc.txt", "wt", encoding="utf-8") as f:
texto = u"Writing with díférént chars"
f.write(texto)
with io.open("abc.txt", encoding="utf-8") as f:
print(f.read())