Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Unable to read file locally on Mac (Encoding error)

Hi,

I'm unable to read the names.txt file locally.

The error :

UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 865: ordinal not in range(128)

The code :

names_file = open("names.txt", encoding="utf-8")
data = names_file.read()
names_file.close()

print(data)

It did worked but only when I removed all the letters whith an accent and I wonder if there was a better solution. So far I tried to save the file with a different encoding and I did modify the encoding inside the script to utf-16, utf-32, latin1 but still no success.

The project is from this vidéo : https://teamtreehouse.com/library/regular-expressions-in-python/introduction-to-regular-expressions/reading-files I download the file from the project.

Any help would be great please.

Nathan Tallack
Nathan Tallack
22,164 Points

How did you create your names.txt file? Did you cut and paste it into an editor? If so, which one? Did you download it? If so, can you provide the link?

1 Answer

The encoding is "latin_1" and not latin1. And you could also just replace it with "iso-8859-1". See if that works?

Thanks for the reply but I still got an error. I should have mention that I was trying with the build tool from sublime text. I just give it a try with Terminal and it worked fine with "utf-8" encoding.