python - _csv.Error : field larger than field limi

我在一个包含非常大字段的 csv 文件中读取了一个脚本:

# example from http://docs.python.org/3.3/library/csv.html?highlight=csv%20dictreader#examples
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

但是,这会在某些 csv 文件上引发以下错误:

_csv.Error: field larger than field limit (131072)

如何分析包含大字段的 csv 文件?跳过包含大量字段的行不是一种选择,因为需要在后续步骤中分析数据。

最佳答案

csv 文件可能包含非常大的字段,因此增加 field_size_limit:

import sys
import csv

csv.field_size_limit(sys.maxsize)

sys.maxsize 适用于 Python 2.x 和 3.x。 sys.maxint 仅适用于 Python 2.x (SO: what-is-sys-maxint-in-python-3)

更新

正如 Geoff 所指出的,上面的代码可能会导致以下错误:OverflowError: Python int too large to convert to C long。 为了避免这种情况,您可以使用以下快速而肮脏的代码(它应该适用于每个使用 Python 2 和 Python 3 的系统):

import sys
import csv
maxInt = sys.maxsize

while True:
    # decrease the maxInt value by factor 10 
    # as long as the OverflowError occurs.

    try:
        csv.field_size_limit(maxInt)
        break
    except OverflowError:
        maxInt = int(maxInt/10)

关于python - _csv.Error : field larger than field limit (131072),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063936/

相关文章:

python - Python 的 any 和 all 函数是如何工作的?

linux - 如何在 grep 中抑制二进制文件匹配结果

python - 在 Python 中将字符串日期转换为时间戳

linux - 如何在 Linux VM 的控制台上向上/向下滚动

linux - 有没有办法按列 'uniq'?

linux - CLOCK_REALTIME 和 CLOCK_MONOTONIC 的区别?

linux - 在fish shell中定义别名

python - 如何检查我是否在 Python 中的 Windows 上运行?

python - 使用 Python 的 os.path,我如何上一个目录?

python - 浅拷贝、深拷贝和普通赋值操作有什么区别?