如何在Python中读取一行csv数据? [英] How to read one single line of csv data in Python?

查看:2107
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆