Python 在“中打开文件”;摇滚乐;滚;模式
我想知道文件Python 在“中打开文件”;摇滚乐;滚;模式,python,file,python-3.x,python-2.x,Python,File,Python 3.x,Python 2.x,我想知道文件open()modevalidation(Python2.7)是怎么回事: 而且,这令人困惑,为什么python3.x的行为不同 前面的回溯很好地解释了这一点: “ValueError:模式字符串必须以r”、“w”、“a”或“U”中的一个开头” “rock&roll”以“r”开头,因此它显然是合法的。Python2.xopen函数实质上将其工作委托给C库fopen函数。在我的系统上,fopen的文档包含: 参数mode指向以以下序列之一开头的字符串(这些序列后面可能有其他字符): 您
open()
modevalidation(Python2.7)是怎么回事:
而且,这令人困惑,为什么python3.x的行为不同 前面的回溯很好地解释了这一点: “ValueError:模式字符串必须以r”、“w”、“a”或“U”中的一个开头”
“rock&roll”以
“r”
开头,因此它显然是合法的。Python2.xopen
函数实质上将其工作委托给C库fopen
函数。在我的系统上,fopen
的文档包含:
参数mode
指向以以下序列之一开头的字符串(这些序列后面可能有其他字符):
您的ock&roll
被视为“附加字符”
在python3中,是(本质上只允许有效字符串)。Ok,但是为什么python3.x的行为不同呢?这就是让我有点困惑的地方。@alecxe——python2.7和python3.x之间有很多不同之处。。。开发人员可能认为,即使系统的
fopen
允许使用“rock&roll”作为文件模式是愚蠢的,因此他们可能提前添加了一些验证。Python 3中的io
系统与传统的Python 2实现非常不同。新的io系统也可以在Python2.7上使用(并在2.6中引入)。如果使用import io,您应该可以看到Py3的行为;io.open('input.txt','rock&roll')
。更多信息:是的,我想说的是,他们只是简单地向函数添加了输入验证。Python 3的行为可以在Python 2上通过io import open的实现。读了mgilson的答案后,我大笑起来
>>> 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
>>> 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'