使用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])
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
你可以像这样得到第一行:
with open('some.csv', newline='') as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
first_line = next(csv_reader)
您可以使用 Pandas 库从庞大的数据集中读取前几行。
import pandas as pd
data = pd.read_csv("names.csv", nrows=1)
您可以在 nrows 参数中指定要读取的行数。
来自Python文档:
虽然模块不直接支持解析字符串,但可以轻松完成:
import csv
for row in csv.reader(['one,two,three']):
print row
只需将字符串数据放入单例列表即可。
仅供参考,获取第一行后可以使用
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
获取 csv 文件中任意行的简单方法
import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
csvFileArray.append(row)
print(csvFileArray[0])
打印一系列行,在本例中是从第 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)
我认为最简单的方法就是最好的方法,在这种情况下(以及大多数其他情况下)是一种不使用外部库 (pandas) 或模块 (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 """
对于 Python3 使用: 我的行=下一个(f)