【问题标题】:Open files in "rock&roll" mode以“摇滚”模式打开文件
【发布时间】:2014-05-27 21:44:28
【问题描述】:

我想知道文件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&amp;roll 模式下打开它。在这种情况下实际使用什么模式打开文件?

请注意,在 python3 上,我不能同时使用 illegalrock&amp;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 的行为不同?

【问题讨论】:

  • 看完mgilson的回答让我笑了

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


【解决方案1】:

前面的回溯很好地解释了它:

“ValueError:模式字符串必须'r'、'w'、'a'或'U'之一开始”

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

【讨论】:

  • 好的,但是为什么 python3.x 的行为不同呢?这让我有点困惑。
  • @alecxe -- python2.7 和 python3.x 之间有很多不同...开发人员可能认为接受“摇滚”作为文件模式是愚蠢的,即使系统的@ 987654323@ 允许它,所以他们可能提前添加了一些验证。
  • Python 3 中的io 系统与传统的 Python 2 实现非常不同。新的 io 系统也可用于 Python 2.7(并在 2.6 中引入)。如果您使用import io; io.open('input.txt', 'rock&amp;roll'),您应该会看到 Py3 的行为。更多信息:docs.python.org/2/library/io.html
【解决方案2】:

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

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

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

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

【讨论】:

  • 是的,我正要说我的猜测是他们只是在函数中添加了输入验证。
  • Python 3 的行为可以通过from io import open 在 Python 2 上实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多