Mirac7
Mirac7

Reputation: 1646

Why do I get a SyntaxError that says "Non-UTF-8 code starting with..."?

I have a script which uses open() to create multiple files. All files are created successfully and it seems that there are no problems, but when attempting to run res.py, it crashes displaying following error:

  File "C:\Users\Mirac\Python\res.py", line 38
SyntaxError: Non-UTF-8 code starting with '\xd7' in file C:\Users\Mirac\Python\res.py on line 38, but no encoding declared;

When opening file through IDLE, I get 'Specify file encoding' window:

The file's encoding is invalid for Python 3.x. 
IDLE will convert it to UTF-8.
What is current encoding of the file?

This is line 38 of res.py:

print("Configuration file updated.")

So, can I set encoding to file during creation, something like this:

open("res.py", "w").encoding("UTF-8")
with open("res.py", "a") as file:
    file.write("File contents here")

If not, how can I fix this problem?

Upvotes: 1

Views: 12923

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

This is not a problem with how you open and write files in Python. It's a problem with Python trying to read your python source files. You need to specify an encoding for your source file so that Python can read the .py file correctly.

You need to figure out what encoding your editor used when writing this file. Add that as a comment to the top of the file (first or second line):

# coding: latin-1

See the Unicode Literals in Python Source Code section of the Python Unicode HOWTO.

Note that the error message you gave is not complete, the following text is part of that:

see http://www.python.org/peps/pep-0263.html for details

The linked PEP 263 explains source code encoding in more detail.

Upvotes: 2

Related Questions