如何使用Python从csv文件中仅打印前10行? [英] How do I print only the first 10 lines from a csv file using Python?
本文介绍了如何使用Python从csv文件中仅打印前10行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Python的新手,我只想打印一个巨大的csv文件的前10行.
I'm new to Python and I'm wanting to print only the first 10 lines of a huge csv file.
到目前为止,这是我的代码,可打印csv文件中的所有行
Here's my code so far that prints all of the lines in the csv file
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'])
推荐答案
您只需在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
这篇关于如何使用Python从csv文件中仅打印前10行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文