IO in python 3 not writing/reading -
this question has answer here:
i copying example book piece of code write , read file has been created (using utf-8). thing code have doesn't print when run it:
#encoding = utf-8 import io f = io.open("abc.txt", "wt", encoding = "utf-8") texto = u"writing díférént chars" f.write(texto) f.close text = io.open("abc.txt", encoding = "utf-8").read() print(text)
you missing parens in call close
:
f.close()
adding prints me in both python2 , python3.
writing buffered io (the default using io.open
) may causes writes deferred -- when writing small amounts of data (less default buffer size). since file never closed, buffer never flushed disk causing subsequent reads see file truncated (the initial state when file gets opened writing).
i'd suggest using contextmanager protocol instead (as won't have think closing files):
# encoding: utf-8 import io io.open("abc.txt", "wt", encoding="utf-8") f: texto = u"writing díférént chars" f.write(texto) io.open("abc.txt", encoding="utf-8") f: print(f.read())
Comments
Post a Comment