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 Regular Expressions in Python Introduction to Regular Expressions Reading Files

sidni ahmed
sidni ahmed
3,329 Points

reading file on my pc?

i am trying to read the same 'names.txt' file one my PC keep getting errors. I have made a directory just for the text file but it does not work.

code is:

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

print(data)

error is:

RESTART: C:/Users/Windows/Desktop/Courses/Python/Test_files/address_book.py Traceback (most recent call last): File "C:/Users/Windows/Desktop/Courses/Python/Test_files/address_book.py", line 2, in <module> data = names_file.read() File "C:\Users\Windows\AppData\Local\Programs\Python\Python35\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 217: invalid continuation byte

4 Answers

Steven Parker
Steven Parker
229,644 Points

:mailbox_with_mail: I got your message!

It looks like your file contents are not being handled by the utf-8 decoder. Is it possible that's not the actual format?

You might try specifying a different format (perhaps utf-16?) in the open statement, or converting your file to another format (perhaps plain ASCII) which can be read without a special decoder.

TypeError: 'encoding' is an invalid keyword argument for this function

So the function open should have the open(name[, mode[, buffering]]) So the Correct Way is:

names_file = open("c:/test/names.txt", "r") data = names_file.read() names_file.close()
Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

Have you tried something like this using the 'r' parameter?

file = open('newfile.txt', 'r')

sidni ahmed
sidni ahmed
3,329 Points

yes, problem is 'names.text' has utf-8 encoding so if i use 'r' parameter it missed out utf-8 characters