Skip to content Skip to sidebar Skip to footer

Unicode Error - Opening *.txt Files With Python

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'

Solution 1:

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())

Post a Comment for "Unicode Error - Opening *.txt Files With Python"