111

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

7 回答 7

155

要仅读取 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
于 2013-06-23T15:29:39.313 回答
43

你可以得到第一行,如:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)
于 2013-06-23T15:29:22.800 回答
27

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

import pandas as pd

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

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

于 2015-06-19T18:46:02.080 回答
15

Python 文档

虽然该模块不直接支持解析字符串,但可以轻松完成:

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

只需将您的字符串数据放入单例列表中。

于 2015-01-23T04:08:39.210 回答
12

仅供参考,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
于 2020-01-31T22:20:07.517 回答
8

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

import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
    csvFileArray.append(row)
print(csvFileArray[0])
于 2016-09-22T03:07:50.793 回答
4

打印一系列行,在本例中为第 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)
于 2020-04-08T14:01:50.327 回答