2

When I try to read a text file like so in python:

x = open("C:\Users\username\Desktop\Hi.txt", 'r')

This error is returned:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I looked around and found this question: "Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3. Apparently I need to duplicate all of the backslashes so Unicode doesn't get all screwed up by what I am trying to do. So I did, but then when I ran print(x) I got this output:

<_io.TextIOWrapper name='C:\\Users\\Sam\\Desktop\\Hi.txt' mode='r' encoding='cp1252'>

What on earth is this, and how do I fix it? I am running python 3.3, doing all of this in IDLE. Thanks.

1 Answer 1

3

You need to use raw strings with Windows-style filenames:

x = open(r"C:\Users\username\Desktop\Hi.txt", 'r')
             ^^

Otherwise, Python's string engine thinks that \U is the start of a Unicode escape sequence - which of course it isn't in this case.

Then, you can't simply print() a file like this, you need to read() it first:

print(x.read())
Sign up to request clarification or add additional context in comments.

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.