Unicode error - opening *.txt files with python

ぐ巨炮叔叔 提交于 2019-12-12 19:40:10

问题


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:


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


来源:https://stackoverflow.com/questions/20588840/unicode-error-opening-txt-files-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!