以“摇滚”模式打开文件

时间:2014-04-14 03:31:44

标签: python file python-3.x python-2.x

我想知道文件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上,我不能同时使用illegalrock&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 个答案:

答案 0 :(得分:17)

Python 2.x open函数实质上将其工作委托给C库fopen函数。在我的系统上,fopen的文档包含:

  

参数mode指向以下列序列之一开头的字符串(其他字符可能遵循这些序列。):

您的ock&roll被视为“其他字符”。

在Python 3中,allowed open modes are more restricted(基本上只允许有效的字符串)。

答案 1 :(得分:16)

之前的追溯很好地解释了它:

  

“ValueError:模式字符串必须,'w','a'或'U'之一开头

“rock&amp; roll”以"r"开头,所以它显然是合法的。