以“摇滚”模式打开文件。

15

我想知道 Python 2.7 中 open() 模式验证的情况:

>>> 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

所以,我不能以非法模式打开文件,但我可以以摇滚模式打开它。在这种情况下,实际上使用哪种模式来打开文件?

请注意,在Python3中,我不能同时使用非法摇滚

>>> 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中行为不同?


读完mgilson的回答后,让我忍俊不禁。 - smac89
2个回答

17

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

  

参数mode指向以以下序列之一开头的字符串(这些序列后面可能跟随其他字符):

您的ock&roll被视为“附加字符”。

在Python 3中,允许使用的打开模式更受限制 (基本上只允许有效的字符串)。


3
没错,我本来想说的是他们很可能只是在该函数中添加了输入验证。 - aruisdante
1
在Python 2中,可以通过from io import open实现Python 3的行为。 - Martijn Pieters

16

前面的回溯信息已经很好地解释了问题:

"ValueError: mode string 必须以 'r'、'w'、'a' 或 'U' 其中之一开头"

"rock&roll" 以 "r" 开头,因此显然是合法的。


好的,但为什么Python3.x的行为不同呢?这让我有点困惑。 - alecxe
3
Python2.7和Python3.x之间有很多不同之处……开发人员可能认为即使系统的fopen允许它,接受"rock&roll"作为文件模式也很愚蠢,因此他们可能提前添加了一些验证。 - mgilson
2
Python 3中的io系统与传统的Python 2实现非常不同。新的io系统也可用于Python 2.7(并在2.6中引入)。如果您使用import io; io.open('input.txt', 'rock&roll'),则应该看到Py3行为。更多信息:https://docs.python.org/2/library/io.html - Ned Deily

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接