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


89

有很多使用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])

您的csv的结构是什么?row当您通过阅读器进行迭代时是什么?
dm03514 2013年

Answers:


141

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

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

38

您可以像这样获得第一行:

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

2
可能最好在f中添加“ with open('csv_file','r')”:csv_reader = csv.reader(f)...”
Sanchit,


13

Python文档中

尽管该模块不直接支持解析字符串,但可以轻松实现:

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

只需将字符串数据放入单例列表即可。


8

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

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

3
要在python3中实现此功能,只需删除“ rb”中的“ b”
Ricky Avina

1
这只是有效,实际上没有delimiter='.'
suvtfopw

1
要回答张贴者的问题,只需在break后面添加一个csvFileArray.append(row),它将仅读取第一行。
StratusBase LLC

4

仅供参考,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

2

要打印行的范围,在这种情况下是从第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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.