如何从CSV文件中读取n行[重复]

vom3gejh  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(96)

此问题在此处已有答案

only reading first N rows of csv file with csv reader in python(3个答案)
昨天关门了。
我试图从一个大的CSV文件中读取一些数据的子集,我已经尝试使用nrows,但它返回以下错误消息,'TypeError:“nrows”是此函数“”的无效关键字参数,不确定如何更正。

with open('file.csv') as csv_file:
    csv_reader = reader(csv_file, nrows=350)
    lines = list(csv_reader)
    print(lines) 

#Aim was to print 350 rows in a list of lists

TypeError: 'nrows' is an invalid keyword argument for this function
polkgigr

polkgigr1#

例如,您可以使用itertools.islicecsv_reader中只读取350行:

from csv import reader
from itertools import islice

with open('file.csv', 'r') as csv_file:
    csv_reader = reader(csv_file)
    lines = list(islice(csv_reader, 0, 350))
    print(lines)

相关问题