我是Python的新手,我想只打印一个巨大的csv文件的前10行。
到目前为止,我的代码打印了csv文件中的所有行
import csv
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
答案 0 :(得分:12)
使用itertools.islice
:
import csv
from itertools import islice
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in islice(reader, 10): # first 10 only
print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
在您了解情况时,您还可以使用operator.itemgetter
使列更容易:
import csv
from itertools import islice
from operator import itemgetter
get_columns = itemgetter('survived', 'pclass', 'name', 'sex', 'age')
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in islice(reader, 10): # first 10 only
print(*get_columns(row))
答案 1 :(得分:11)
你可以在10行之后break
。
import csv
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for i,row in enumerate(reader):
print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
if(i >= 9):
break
答案 2 :(得分:1)
Adrien El Zein的回答足以满足您的提问。但是,如果您认为它有点令人困惑(我不这么认为):
import csv
counter = 0
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in enumerate(reader):
print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
counter += 1
if counter >= 9:
break
我所做的就是将变量i
重命名为counter
。另外,对于替代循环:
import csv
counter = 0
with open('titanic.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in enumerate(reader):
print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
while counter < 10:
counter += 1
else:
break
我尝试使用Python 3.4.3测试while-else
循环(不确定您拥有哪个版本)并且可以告诉您它正常工作。
答案 3 :(得分:0)
要从csv文件中获取前N行,请选择字段
#for python 3
import csv
from operator import itemgetter
N=11 # to get 10 rows need use 10+1=11
fname='titanic.csv'
get_columns=itemgetter('survived', 'pclass', 'name', 'sex', 'age')
with open(fname,'r') as csvfile:
reader = csv.DictReader(csvfile.readlines()[0:N])
[print(*get_columns(row)) for row in reader]
# or for all fields : use [print(row)) for row in reader]