0

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)
eduardo0
  • 91
  • 1
  • 8

1 Answers1

1

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())
anthony sottile
  • 61,815
  • 15
  • 148
  • 207
  • Are you quite sure binary writes are unbuffered (that only files opened as text are subject to output buffering)? Could you point to documentation to that effect? (I'm also hesitant to say that the writes are deferred -- that sounds like an assertion that they *won't* be visible until flushed, as opposed to an assertion that they *may not* be visible until flushed, subject to the difference between write size and buffer size, the local standard C library's write buffering behavior, and other runtime details and configuration). – Charles Duffy Sep 12 '17 at 02:34
  • I made no comment about binary writes, which are also buffered by default -- I see how you could pull that from my answer in it's current state so I'll update accordingly :) The buffering also happens independently of the C library as it's [implemented in python](https://docs.python.org/3/library/io.html#io.BufferedWriter). – anthony sottile Sep 12 '17 at 03:10