Skip to main content
 首页 » 编程设计

python之在 python 2.7 中打开文件的正确方法是什么

2025年05月04日17bluestorm

我试图在 IDLE 中打开一个 txt 文件,但它给了我一个错误。 我无法弄清楚我的文件名中的 f 发生了什么,或者为什么单个 '\' 在错误消息中变成了 double。

>>>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' 

请您参考如下方法:

反斜杠用于转义序列 - 在您的情况下,罪魁祸首是 \f 这是换页符。您还可以在现代 Windows 系统上使用正斜杠以及其他替代方法。

使用原始字符串:

f=open(r'D:\programs\python 2.7.10\programs\foo.txt','r') 

理想情况下,您应该使用 with 语句,以便在出现异常或 with block 退出时自动关闭文件,例如:

with open(r'D:\programs\python 2.7.10\programs\foo.txt','r') as f: 
    # do stuff with `f`