[英]I am trying to read the content of a file through a python program
The problem is related to the text file path. 问题与文本文件路径有关。 As soon as i copy the text file in the directory of the python program and run it,it runs successfully.
一旦我将文本文件复制到python程序的目录中并运行它,它就会成功运行。 Here is the code->
这是代码->
ana=open("C:\Users\HP\Downloads\practice1.txt","r")
pj=ana.read()
ana.close()
pj=pj.splitlines()
print(pj)
for i in pj:
print(i)
The error displayed is-> 显示的错误是->
[unicode error] 'unicodeescape' codec can't decode bytes in position 2-3:truncated\UXXXXXXXX escape
Please help! 请帮忙!
Try any of the below : 尝试以下任何一种方法:
ana=open(r'C:\Users\HP\Downloads\practice1.txt')
ana=open('C:\\Users\\HP\\Downloads\\practice1.txt')
ana=open('C:/Users/HP/Downloads/practice1.txt')
The backslash character (\\) has a special meaning when it appears in a string (or bytes) literal in Python. 当反斜杠字符(\\)出现在Python的字符串(或字节)文字中时,具有特殊含义。 Backslash is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
反斜杠用于转义具有特殊含义的字符,例如换行符,反斜杠本身或引号字符。
ana=open("C:\Users\HP\Downloads\practice1.txt","r")
In your example, Python is trying to escape the U
, H
, D
and p
characters because they have backslashes in front of them! 在您的示例中,Python试图转义
U
, H
, D
和p
字符,因为它们前面有反斜杠!
Fortunately, Python provides us with a syntax that allows us to write strings containing literal backslash characters. 幸运的是,Python为我们提供了一种语法,该语法使我们能够编写包含文字反斜杠字符的字符串。 Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R';
字符串和字节文字都可以选择以字母“ r”或“ R”为前缀; such strings are called raw strings and treat backslashes as literal characters.
这样的字符串称为原始字符串 ,并将反斜杠视为原义字符。
ana=open(r"C:\Users\HP\Downloads\practice1.txt","r")
Now the backslash characters are treated as normal characters, and no escaping is attempted. 现在,将反斜杠字符视为普通字符,并且不尝试转义。
You can read more about this in the Python reference documentation about literals https://docs.python.org/3/reference/lexical_analysis.html#literals 您可以在有关文字的Python参考文档中阅读有关此内容的更多信息https://docs.python.org/3/reference/lexical_analysis.html#literals
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.