[英]What's the proper way to open a file in python 2.7?
I'm trying to open a txt file in IDLE but it gives me an error. 我试图在IDLE中打开一个txt文件,但它给我一个错误。 I can't figure out what happens to the f in my file name or why the single '\\' becomes double in the error message. 我无法弄清楚文件名中的f会发生什么,或者为什么错误消息中的单个“ \\”会变成双精度。
>>>f=open('D:\programs\python 2.7.10\programs\foo.txt','r')
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
f=open('D:\programs\python 2.7.10\programs\foo.txt','r')
IOError: [Errno 22] invalid mode ('r') or filename: 'D:\\programs\\python 2.7.10\\programs\x0coo.txt'
Backslashes are used for escape sequences - in your case the culprit is \\f
which is the form-feed character. 反斜杠用于转义序列-在您的情况下,罪魁祸首是\\f
,它是换页符。 You can also use forward slashes on modern Windows systems as well as an alternative. 您还可以在现代Windows系统上以及其他方法上使用正斜杠。
Use a raw string: 使用原始字符串:
f=open(r'D:\programs\python 2.7.10\programs\foo.txt','r')
Ideally though, you should use the with
statement so that it automatically closes the file in case of exceptions or when the with block exits, eg: 不过,理想情况下,应该使用with
语句,以便在出现异常或with块退出时,它自动关闭文件,例如:
with open(r'D:\programs\python 2.7.10\programs\foo.txt','r') as f:
# do stuff with `f`
You have a funny character "\\x0c" in your path. 您的路径中有一个有趣的字符“ \\ x0c”。 Its "f" in hex. 十六进制的“ f”。 Python doesn't understand. Python不懂。 That's why ASCII gives an error. 这就是ASCII给出错误的原因。 Rename your file into something nicer and you will be fine. 将文件重命名为更好的名称,这样就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.