Skip to main content
 首页 » 编程设计

python之如何在字段数太大之前读取csv

2025年05月04日15落叶无声

我有一个 csv,我用它读入:

df = pd.read_csv("file.csv") 

所有行都有 37 个字段,直到有一个有 38 个字段,从那里开始它就被破坏了。我怎样才能只读取包含 37 个字段的行?

请您参考如下方法:

来自文档:http://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.read_csv.html

error_bad_lines : boolean, default True

Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will dropped from the DataFrame that is returned.

所以你可以使用:

df = pd.read_csv("file.csv", error_bad_lines=False) 

但最好编辑您的 .csv 文件并正确修复相关行。 :)