I really think Processing’s
saveStrings() are super-great, and I use them all the time when I need to read text from and write text into a file.
But I’m writing some instructional materials and I wanted to give my readers a taste of Python’s common
with open(file ... as f: idioms. Just in case they want to use other Python interpreters somewhere else.
For reading Unicode strings from a file
io.open() seemed to work better than ‘normal’
open() (non-ASCII characters encoding came wrong otherwise):
from io import open as io_open
with io_open("data/my_unicode_strings.txt", 'r') as f:
line_list = f.readlines()
Then, for wrinting strings…
open() works fine, but
# from io import open # not a good idea because
with open(output_path, 'w') as f: # open(output_path, 'w', enconding='utf-8') # not working for me
for li in line_list:
f.write(li + u'ãéíôú') # works fine with 'normal' open()
So I’m a bit frustrated with this inconsistency. Any insights on what I might be missing?
Untested, but have you tried using codecs.open instead?
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
as documented in the Python 2 unicode howto?
Thanks for caring. I will have a look!
But I guess It’s just a rant with no relevance. Few students will use these constructs I guess, and when using Python outside Processing they will have to look up anyway so I guess the small
io_open to read vs
open to write inconsistency will be irrelevant…
It is an interesting point, though. If making it consistent had no downsides, it would be a clear win to build a change into Python mode.
But it seems like maybe making it consistent would confuse students about normal Python 2?
On the other hand, Python 2 is now very retired. So maybe that potential confusion is a minimal downside…
I have not tested much, but documentation I’ve seen somewhere tells the Python 2
io.open should behave exactly like Python 3
open, so I was surprised I couldn’t make it work in write mode