从Python中读取文件,奇怪的错误 [英] Reading from file in Python, weird error
本文介绍了从Python中读取文件,奇怪的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
f = open("C:\Users\aleed_000\Desktop\dis.txt","r")
print (f.read())
f.close()
任何人都可以解释为什么不能从名为dis.txt的文件中读取吗?当我尝试运行它时,它说错误,然后突出显示打开的括号.我不明白这是怎么回事.
Can anyone explain why this doesn't read from my file named dis.txt? When I tried to run it, it says error, and then highlights the open paren. I don't understand what is wrong.
推荐答案
使用原始字符串或通过在其前面加上另一个'\'
来对每个'\'
进行转义:
Use a raw string or escape each '\'
by prefixing another '\'
to it:
因为C:\Users\aleed_000\Desktop\dis.txt
实际上是这样解释的:
because C:\Users\aleed_000\Desktop\dis.txt
is actually interpreted like this:
>>> print ("C:\Users\aleed_000\Desktop\dis.txt") # '\a' gets escaped
C:\Usersleed_000\Desktop\dis.txt
原始字符串:
>>> print (r"C:\Users\aleed_000\Desktop\dis.txt") #notice the r at the start
C:\Users\aleed_000\Desktop\dis.txt
每个'\'
退出:
>>> print ("C:\\Users\\aleed_000\\Desktop\\dis.txt")
C:\Users\aleed_000\Desktop\dis.txt
这篇关于从Python中读取文件,奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文