有许多使用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])
答案 0 :(得分:108)
要只阅读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
答案 1 :(得分:20)
你可以得到第一行,如:
with open('some.csv', newline='') as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
first_line = next(csv_reader)
答案 2 :(得分:16)
您可以使用Pandas库从巨大的数据集中读取前几行。
import pandas as pd
data = pd.read_csv("names.csv", nrows=1)
您可以在nrows参数中提及要读取的行数。
答案 3 :(得分:10)
虽然模块不直接支持解析字符串,但可以轻松完成:
import csv
for row in csv.reader(['one,two,three']):
print row
将字符串数据放入单例列表中。
答案 4 :(得分:5)
获取csv文件中任何行的简单方法
import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
csvFileArray.append(row)
print(csvFileArray[0])
答案 5 :(得分:5)
仅供参考,在获取第一行以获取文件的其余部分之后,可以使用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
答案 6 :(得分: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)