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

有很多使用 python 读取 csv 数据的例子,比如下面这个:

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

我只想读取一行数据并将其输入到各种变量中。我该怎么做?我到处都找过了。

我的代码只检索 i 的值,其他值都不检索

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])
313974 次浏览

you could get just the first row like:

with open('some.csv', newline='') as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
first_line = next(csv_reader)

要只读取 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

来自 Python 文档:

虽然该模块不直接支持解析字符串,但它可以很容易地完成:

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

只需将字符串数据放入一个单例列表。

你可以使用熊猫图书馆阅读从庞大的数据集的前几行。

import pandas as pd


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

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

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

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

仅供参考,在获得第一行之后可以使用 for循环来获得文件的其余部分:

with open('file.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader)  # gets the first line
for row in reader:
print(row)       # prints rows 2 and onward

打印行的范围,在本例中是从第4行到第7行

import csv


with open('california_housing_test.csv') as csv_file:
data = csv.reader(csv_file)
for row in list(data)[4:7]:
print(row)

我认为最简单的方法就是最好的方法,在这种情况下(在大多数其他情况下)就是不使用外部库(Pandas)或模块(csv)的方法。所以,答案很简单。

""" no need to give any mode, keep it simple """
with open('some.csv') as f:
""" store in a variable to be used later """
my_line = f.nextline()
""" do what you like with 'my_line' now """