0

When I run this code:

str1= "Ram's birthplace is “Ayodhya” in Uttar Pradesh"
file = open("abc.txt","w")
file.write(str1)

I got error:

SyntaxError: Non-ASCII character '\xe2' in file, no encoding declared

3
  • 1
    file = open("abc.txt","w",encoding="utf-8"), or maybe it's decoding Commented Jan 30, 2018 at 7:14
  • are you using python 2.x ? Commented Jan 30, 2018 at 7:21
  • Same error still. I am using 2.7 Commented Jan 30, 2018 at 7:54

2 Answers 2

1

Looks like you need to set the encoding on the top of your script to prevent this error.

Ex:

# -*- coding: utf-8 -*-
Sign up to request clarification or add additional context in comments.

2 Comments

Do i need to import anything ?
No. Just set the above snippet to the first line of your script.
0

As Rakesh pointed out, you can set an encoding cookie at the top of your script so that it handles non-ascii characters.

Alternatively, you could replace the double quotation marks around Ayodhya with ascii quotation marks:

str1= "Ram's birthplace is \"Ayodhya\" in Uttar Pradesh"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.