访问csv文件的第N行的最佳方法 [英] Best way to access the Nth line of csv file

查看:107
本文介绍了访问csv文件的第N行的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须访问CSV文件中的第N行.

I have to access the Nth line in a CSV file.

这就是我所做的:

import csv

the_file = open('path', 'r')
reader = csv.reader(the_file)

N = input('What line do you need? > ')
i = 0

for row in reader:
    if i == N:
        print("This is the line.")
        print(row)
        break

    i += 1

the_file.close()

...但是感觉并不理想.编辑精度:如果文件很大,我不想遍历所有行,也不需要将整个文件加载到内存中.

...but this does not feel optimal. Edit for precision: If the file is huge, I do not want to go through all the lines and I do not want to have to load the whole file into memory.

我确实希望像reader[N]这样的东西存在,但我没有找到它.

I do hope something like reader[N] exists, but I have not found it.

编辑答案:此行(来自所选答案)是我想要的:

Edit for answer: This line (coming from chosen answer) is what I was looking for:

next(itertools.islice(csv.reader(f), N, None)

推荐答案

它没有什么区别,但是使用enumerate而不是使自己的计数器变量更干净.

It makes little difference but it is slightly cleaner to use enumerate rather than making your own counter variable.

for i, row in enumerate(reader):
    if i == N:
        print("This is the line.")
        print(row)
        break

您还可以使用针对这种情况设计的itertools.islice-在不将整个内容读取到内存的情况下访问可迭代对象的特定片段.它应该比遍历不需要的行更有效率.

You can also use itertools.islice which is designed for this type of scenario - accessing a particular slice of an iterable without reading the whole thing into memory. It should be a bit more efficient than looping through the unwanted rows.

with open(path, 'r') as f:
    N = int(input('What line do you need? > '))
    print("This is the line.")
    print(next(itertools.islice(csv.reader(f), N, None)))

但是,如果您的CSV文件很小,则只需将整个内容读入一个列表即可,然后您可以按照常规方式使用索引来访问该列表.这还有一个优点,您可以按随机顺序访问多个不同的行,而不必重置csv阅读器.

But if your CSV file is small, just read the entire thing into a list, which you can then access with an index in the normal way. This also has the advantage that you can access several different rows in random order without having to reset the csv reader.

my_csv_data = list(reader)
print(my_csv_data[N])

这篇关于访问csv文件的第N行的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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