从CSV文件读取特定行 [英] Reading a specific line from CSV file

查看:132
本文介绍了从CSV文件读取特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十行的CSV文件。从这个文件中,我只想要第四行。最快的方法是什么?我正在寻找类似的东西:

I have a ten line CSV file. From this file, I only want the, say, fourth line. What's the quickest way to do this? I'm looking for something like:

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    print reader[3]

其中 reader [3] 显然是我想要实现的语法错误。如何将阅读器移至第4行并获取内容?

where reader[3] is obviously incorrect syntax for what I want to achieve. How do I move the reader to line 4 and get it's content?

推荐答案

如果只有10行,则可以加载整个文件放入列表:

If all you have is 10 lines, you can load the whole file into a list:

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    rows = list(reader)
    print rows[3]

对于较大的文件,请使用 itertools。 islice()

For a larger file, use itertools.islice():

from itertools import islice

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    print next(islice(reader, 3, 4))

这篇关于从CSV文件读取特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆