2

How do I read in a text file in python 3.3.3 and store it in a variable? I'm struggling with this unicode coming from python 2.x

Mel
  • 5,837
  • 10
  • 37
  • 42
RocketTwitch
  • 285
  • 5
  • 17

1 Answers1

2

Given this file:

utf-8:   áèíöû

This works as you expect (IFF utf-8 is your default encoding):

with open('/tmp/unicode.txt') as f:
    variable=f.read()

print(variable)  

It is better to explicitly state your intensions if you are unsure what the default is by using a keyword argument to open:

with open('/tmp/unicode.txt', encoding='utf-8') as f:
    variable=f.read()

The keyword encodings supported are in the codec module. (For Python 2, you need to use codecs open to open the file rather than Python 2's open BTW.)

dawg
  • 98,345
  • 23
  • 131
  • 206
  • You don't need to use 'with' and 'as'. You can just use 'f = open(args)' – Ecko May 17 '16 at 13:52
  • 1
    In this case true, but using `with` is a good habit. Consider the differences of using `open` and catching the exception and `read` and then catching a different exception. Using `with` as a matter of habit allows more straight forward `try/except` blocks to be added. Look at [this](http://stackoverflow.com/questions/3642080/using-python-with-statement-with-try-except-block) and [the PEP](https://www.python.org/dev/peps/pep-0343/) – dawg May 17 '16 at 15:02