以“摇滚&滚”模式打开文件
我在想,关于文件的 open()
模式验证(Python2.7)到底是怎么回事:
>>> with open('input.txt', 'illegal') as f:
... for line in f:
... print line
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not 'illegal'
>>> with open('input.txt', 'rock&roll') as f:
... for line in f:
... print line
...
1
2
3
所以,我不能以 illegal
模式打开文件,但我可以以 rock&roll
模式打开。那么在这种情况下,实际上使用了什么模式来打开文件呢?
注意,在 Python3 中,我不能使用 illegal
和 rock&roll
这两种模式:
>>> with open('input.txt', 'rock&roll') as f:
... for line in f:
... print(line)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid mode: 'rock&roll'
>>> with open('input.txt', 'illegal') as f:
... for line in f:
... print(line)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid mode: 'illegal'
而且,这让我感到困惑,为什么在 Python3.x 中行为会不同呢?
2 个回答
16
之前的错误信息解释得很清楚:
“值错误:模式字符串必须以 'r'、'w'、'a' 或 'U' 开头”
“rock&roll” 是以 "r"
开头的,所以看起来是合法的。
17
Python 2.x中的open
函数其实是把工作交给了C语言库里的fopen
函数。在我的系统上,fopen
的文档里提到:
参数
mode
是一个字符串,它的开头必须是以下几种格式之一(后面可以跟其他字符)。
你的ock&roll
就算是“其他字符”。
在Python 3中,允许的打开模式更加严格(基本上,只允许有效的字符串)。