read()的文件大小限制?

时间:2016-12-24 17:23:11

标签: python macos python-2.7 file python-3.x

我在尝试使用Python 3.5加载大型文件时遇到了问题。使用不带参数的read()有时会提供OSError: Invalid argument。然后我尝试只阅读部分文件,它似乎工作正常。我已经确定它在2.2GB附近开始失败,下面是示例代码:

>>> sys.version
'3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> x = open('/Users/username/Desktop/large.txt', 'r').read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
>>> x = open('/Users/username/Desktop/large.txt', 'r').read(int(2.1*10**9))
>>> x = open('/Users/username/Desktop/large.txt', 'r').read(int(2.2*10**9))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

我也注意到在Python 2.7中不会发生这种情况。这是在Python 2.7中运行的相同代码:

>>> sys.version
'2.7.10 (default, Aug 22 2015, 20:33:39) \n[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)]'
>>> x = open('/Users/username/Desktop/large.txt', 'r').read(int(2.1*10**9))
>>> x = open('/Users/username/Desktop/large.txt', 'r').read(int(2.2*10**9))
>>> x = open('/Users/username/Desktop/large.txt', 'r').read()
>>>

我正在使用OS X El Capitan 10.11.1。

这是一个错误还是应该使用另一种方法来读取文件?

1 个答案:

答案 0 :(得分:6)

是的,你碰到了一个错误。

好消息是其他人也发现了它,并且已经在Python bug跟踪器中为它创建了一个问题,请参阅:Issue24658 - open().write() fails on 2 GB+ data (OS X)。这似乎是平台所依赖的(仅限OS-X),并且在使用read和/或write时可重现。显然,在OS-X的libc实现中实现fread.c的方式存在问题,请参阅here

坏消息它仍处于打开状态(并且当前处于非活动状态),所以,您必须等到它被解决。无论哪种方式,如果您对具体细节感兴趣,您仍然可以查看那里的讨论。

作为一种解决方案,我非常确定你可以解决问题,直到通过读取块并在处理过程中链接块来修复它。写作时也一样。不幸的是,它可能会成功。