如何使用 Python 仅打印 csv 文件的前 10 行?

新手上路,请多包涵

我是 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'])

原文由 Adorabubble 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 718
2 个回答

你可以在 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

原文由 Adrien El Zein 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 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))

原文由 Jon Clements 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题