Can't get python to read my .txt file on OS X

user206018 picture user206018 · Mar 11, 2013 · Viewed 9.4k times · Source

I'm trying to get IDLE to read my .txt file but for some reason it won't. I tried this same thing at school and it worked fine using a Windows computer with Notepad, but now using my Mac with IDLE won't read (or find) my .txt file.

I made sure they were in the same folder/directory and that the file was formatted in plain text, still I get errors. Here's the code I was using:

def loadwords(filename):

   f = open(filename, "r")
   print(f.read())
   f.close()
   return

filename = input("enter the filename: ")
loadwords(filename)

and here is the error I got after I enter the file name "test.txt" and press enter:

Traceback (most recent call last):
  File "/Computer Sci/My programs/HW4.py", line 8, in <module>
    loadwords(filename)
  File "/Computer Sci/My programs/HW4.py", line 4, in loadwords
    print(f.read())
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

Answer

L&#230;ti picture Læti · Mar 11, 2013

The error you see means your Python interpreter tries to load the file as ASCII chars, but the text file you're trying to read is not ASCII encoded. It's probably UTF-8 encoded (the default in recent OSX systems).

Adding the encoding to the open command should work better:

f = open(filename, "r" "utf8")

Another way to correct that, would be to go back to TextEdit with your file and then select Duplicate (or Save as shift-cmd-S) where you'll be able to save your file again, but this time choosing the ASCII encoding. Though you might need to add ASCII in the encodings option list if it is not present.

This other question and accepted answer provides some more thoughts about the way to choose the encoding of the file you're reading.