简体   繁体   English

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

[英]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.

相关问题 将Python从2.6更新到2.7时更新Python包的正确方法是什么? - What's the proper way to update Python packages when updating Python from 2.6 to 2.7? 从Python 2.7的同一文件夹导入另一个文件的正确方法是什么? - What's the right way to import another file from the same folder in Python 2.7? 适当的方式做按位差异? (python 2.7) - Proper way to do bitwise difference? (python 2.7) 在python 2.7中相对导入的正确方法 - Proper way to relative import in Python 2.7 在 Python 2.7 中序列化和反序列化对象列表的最快方法是什么? - What's the fastest way to serialize and deserialize a list of objects in Python 2.7? 在Python2.7中将列表转换为字典的最佳方法是什么 - What’s the best way to Convert a list to dict in Python2.7 在Python 2.7中保存/加载大型列表的最快方法是什么? - What's the fastest way to save/load a large list in Python 2.7? 使用python 2.7打开.mat文件 - open .mat file with python 2.7 模拟在Python 2.7中访问时引发异常的可下标属性的正确方法是什么? - What is the proper way to mock a subscriptable property that raises an exception when accessed in Python 2.7? 在正则表达式 python 中排除大写单词的正确方法是什么 - What's the proper way to exclude uppercase word/s in regex python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM