1

This is my first question here.

I am running the following:

  • Sublime Text 3
  • OS 10
  • Python 3.6

I am trying to open and print on Sublime a .txt file. I am using the following code:

myfile = open("/stanford.txt", "r")
contents = myfile.read()

and this is the error message that I get:

Traceback (most recent call last):
 File "/Users/me/python/Test1.py", line 11, in <module> 
  contents = myfile.read()
 File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
  return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 173: ordinal not in range(128)
[Finished in 0.1s with exit code 1]

The 2 lines of code above work on Sublime Text 3 when I run it using Python 2.7. It also works when I run them on Terminal (using Python3). However, they do not work when I try them in IDLE: there I get exactly that same error message that Sublime Text 3 is giving me when I run them in Python3.

This is my build configuration on Sublime Text 3:

{
 "cmd": ["/Library/Frameworks/Python.framework/Versions/3.6/bin/python3", "$file"],
 "selector": "source.python",
 "file_regex": "file \"(...*?)\", line([0-9]+)"
}

I have also tried adding "PYTHONIOENCODING" but still the same error message:

{
 "cmd": ["/Library/Frameworks/Python.framework/Versions/3.6/bin/python3", "$file"],
 "selector": "source.python",
 "file_regex": "file \"(...*?)\", line([0-9]+)",
 "env": {"PYTHONIOENCODING": "utf8"}
}

(I have also tried "utf-8" with the dash instead of the above. Same error message).

What do I need to do so that Sublime Text 3 can read the file?

Thank you

Edit: I don't think this issue is a duplicate of the other? This works on Terminal for me but not on Sublime Text 3.

Edit2: I have noticed that if I remove the apostrophes (') contained in the text file, I get to open the file with no problems. The error only occurs when I add the apostrophes back to the text file.

Leon S
  • 153
  • 1
  • 13
  • 3
    Possible duplicate of [UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1](https://stackoverflow.com/questions/10561923/unicodedecodeerror-ascii-codec-cant-decode-byte-0xef-in-position-1) – Murtuza Z Mar 13 '18 at 09:40

1 Answers1

4

Ok, I finally figured it out.

I added the following to the open function:

, encoding="utf-8")

And it worked. I'm still trying to figure out a way to make this permanent to my Python3 on Sublime.

Leon S
  • 153
  • 1
  • 13