当前我的桌面上有一个"过客.txt"的文件,它的字符集是utf-8,另外它的内容如下所示


现我想通过python程序想读取这个文件中的内容,代码如下:
# -*- coding: utf-8 -*-*
f = open(file="C:\Users\Administrator\Desktop\过客.txt",mode="r",encoding="utf-8")
print(f.read())
f.close()
执行代码显示如下错误信息:

这是因为windows下文件的路径是以"\",然而反斜杠"\"在python中有着转义字符的意义,所以在py文件中写windows文件路径的时候,要特别注意反斜杠"\"的使用,以下三种方式可以解决上面的报错信息
第一种方法:(再添加一个反斜杠"\")
f = open(file="C:\\Users\Administrator\Desktop\过客.txt",mode="r",encoding="utf-8")

第二种方法:(在路径开头加r)
f = open(file=r"C:\Users\Administrator\Desktop\过客.txt",mode="r",encoding="utf-8")

第三种方法:(写成linux系统下的路径模式)
f = open(file="C:/Users/Administrator/Desktop/过客.txt",mode="r",encoding="utf-8")

转载于:https://www.cnblogs.com/chenliangc/articles/11572452.html
63




被折叠的 条评论
为什么被折叠?



