ale*_*cxe 15 python file python-2.x python-3.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
Run Code Online (Sandbox Code Playgroud)
所以,我无法在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'
Run Code Online (Sandbox Code Playgroud)
而且,这很令人困惑,为什么python3.x的行为不同?
Gre*_*ill 17
Python 2.x open函数实质上将其工作委托给C库fopen函数.在我的系统上,文档fopen包含:
该参数
mode指向以下列序列之一开头的字符串(其他字符可能遵循这些序列.):
您ock&roll被视为"其他角色".
在Python 3中,允许的打开模式受到更多限制(实质上,只允许有效的字符串).
mgi*_*son 16
之前的追溯很好地解释了它:
"ValueError:模式字符串必须以 'r','w','a'或'U'之一开头 "
"摇滚乐"开头"r",所以它显然是合法的.
| 归档时间: |
|
| 查看次数: |
653 次 |
| 最近记录: |