如何在Python中读取一行csv数据?

有很多使用python读取csv数据的例子,像这样:

import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) 

我只想读取一行数据并将其input到各种variables中。 我怎么做? 我到处寻找一个工作的例子。

我的代码只检索我的值,而没有其他值

 reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in reader: i = int(row[0]) a1 = int(row[1]) b1 = int(row[2]) c1 = int(row[2]) x1 = int(row[2]) y1 = int(row[2]) z1 = int(row[2]) 

要只读取csv文件的第一行,请使用reader对象的next()

 with open('some.csv', newline='') as f: reader = csv.reader(f) row1 = next(reader) # gets the first line # now do something here # if first row is the header, then you can do one more next() to get the next row: # row2 = next(f) 

要么 :

 with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: # do something here with `row` break 

你可以得到像第一行:

 csv_reader = csv.reader(f) csv_headings = next(csv_reader) first_line = next(csv_reader) 

您可以使用Pandas库来读取大数据集中的前几行。

 import pandas as pd data = pd.read_csv("names.csv", nrows=1) 

您可以在nrows参数中提及要读取的行数。

从Python文档 :

虽然模块不直接支持parsingstring,但可以轻松完成:

 import csv for row in csv.reader(['one,two,three']): print row 

只要将你的string数据放入一个单例列表。

在csv文件中获取任何行的简单方法

 import csv csvfile = open('some.csv','rb') csvFileArray = [] for row in csv.reader(csvfile, delimiter = '.'): csvFileArray.append(row) print(csvFileArray[0])