最近用Python读取文件,发现用 ‘\‘ 会报错。
‘\‘是Python的转义字符,如果路径中存在‘\t‘或者‘\r‘这样的特殊字符,‘\‘就无法起到目录跳转的作用,因此报错。解决办法就是告诉系统‘\‘不是转义字符,‘\\‘就起这种作用,现给出一个示例。
方式一:
#使用绝对路径 双反斜杠(python中\具有转义作用) with open(‘E:\\use\\data.txt‘) as file_object: contents = file_object.read() print(contents.rstrip())
方式二:
#加转义符r 即告诉系统不转义 with open(r‘E:\use\data.txt‘) as file_object: contents = file_object.read() print(contents.rstrip())
方式三:
#使用绝对路径 正斜杠 with open(‘E:/use/data.txt‘) as file_object: contents = file_object.read() print(contents.rstrip())
原文:https://www.cnblogs.com/Jungle1219/p/12720960.html