如何在 Python 中读取一行 csv 数据? [英] How to read one single line of csv data in Python?
本文介绍了如何在 Python 中读取一行 csv 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用python读取csv数据的例子有很多,比如这个:
There is a lot of examples of reading csv data using python, like this one:
import csv
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
我只想读取一行数据并将其输入到各种变量中.我怎么做?我到处寻找工作示例.
I only want to read one line of data and enter it into various variables. How do I do that? I've looked everywhere for a working example.
我的代码只检索 i 的值,不检索其他值
My code only retrieves the value for i, and none of the other values
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 文件的第一行,请使用 next()
在阅读器对象上.
To read only the first row of the csv file use next()
on the reader object.
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 中读取一行 csv 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文