简体   繁体   English

有没有办法只在python中读取csv文件中的标题?

[英]Is there a way to only read the header from a csv file in python?

I was wondering if there was a way to only read the header info from a csv file without loading the whole file. 我想知道是否有办法只读取csv文件中的标题信息而不加载整个文件。 I'm dealing with large csv files and would rather not have to load the whole thing. 我正在处理大型csv文件,而不是必须加载整个东西。

Thanks! 谢谢!

You wouldn't normally read the whole file anyway. 你通常不会阅读整个文件。 Just create the CSV reader and call next() on it once. 只需创建CSV阅读器并在其上调用next()一次。

import csv
f = open('myfile.csv')
reader = csv.reader(f)
header = reader.next()
with open(filename) as in_file:
    csv_reader = csv.reader(in_file)
    header = next(csv_reader)

This works because csv.reader() returns a generator , not a list. 这是因为csv.reader()返回生成器而不是列表。 It will only output data if next() is called (ie by using next(csv_reader) or by using it in a for loop, like for row in csv_reader ). 如果调用next() ,它将仅输出数据(即通过使用next(csv_reader)或在for循环中使用它,就像for row in csv_reader )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM