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

标签 python python-3.x csv

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

最佳答案

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

关于python - 如何使用 Python 仅打印 csv 文件的前 10 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088512/

相关文章:

python - SWIG 生成无效的 Python 包装器代码

python - 在 Python 中创建两个具有相同值的不可变对象(immutable对象)

python - 在python中填充两条曲线之间的区域

python - 从列表创建组合而不考虑相邻元素

mysql - 读取 csv 时出现内存错误

python - CSV dtype 中的 numpy rearray 有很多列,但 shape 只显示一行,这是为什么?

python - Pandas 读取带有多个空格的 csv 并解析日期

python - 在 NumPy 数组的行中的特定位置插入零行

multithreading - ThreadPoolExecutor 与 threading.Thread

python - 如何将 DirectInput 键发送到 Python 中的非事件窗口