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

disho6za  于 2022-12-06  发布在  Python
关注(0)|答案(8)|浏览(205)

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

dly7yett1#

要只读取csv文件的第一行,请在读取器对象上使用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
iszxjhcz

iszxjhcz2#

您可以只得到第一行,例如:

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

holgip5t3#

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

import pandas as pd

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

您可以在nrows参数中指定要读取的行数。

lsmd5eda

lsmd5eda4#

仅供参考,可以在获取第一行后使用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
x6492ojm

x6492ojm5#

在Python文档中:
虽然该模块不直接支持解析字符串,但可以很容易地做到:

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

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

agxfikkp

agxfikkp6#

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

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

w7t8yxp57#

打印一系列行,在本例中为从第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)
lokaqttq

lokaqttq8#

我认为最简单的方法就是最好的方法,在这种情况下(以及在大多数其他情况下)是不使用外部库(panda)或模块(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 """

相关问题