简体   繁体   English

DictReader fieldnames vs csv reader第一行

[英]DictReader fieldnames vs csv reader first row

I need to check the column headers in a csv file, and only need the header values for this task, not the values below (yet). 我需要检查csv文件中的列标题,并且只需要此任务的标头值,而不是下面的值(尚未)。 Right now I am using DictReader and fieldnames to get column headers, mainly because the code is much clearer as to what is occurring using this method. 现在我使用DictReader和fieldnames来获取列标题,主要是因为使用此方法时代码更清晰。 Is there any reason (performance or otherwise) to just use the standard csv reader, read in the top column as headers, and then close the file? 是否有任何理由(性能或其他方面)只使用标准的csv阅读器,在顶部列中读取标题,然后关闭文件?

I would imagine that the DictReader would be only slightly less efficient than the csv reader (I have never seen benchmarks though). 我会想象DictReader的效率会略低于csv阅读器(我从未见过基准测试)。 What the DictReader does offer is better readability. DictReader提供的是更好的可读性。 Anyone reading your code will be able to see what is going on when you access a column 阅读代码的任何人都可以看到访问列时发生的情况

reader = csv.DictReader(f.open)
for line_dict in reader:
   line_dict['First Column']
   line_dict['Second Column']

opposed to just numerical indexes of the csv reader. 与csv阅读器的数字索引相反。 If you are working with files with many columns, having to remember indexes to column names can be maddening. 如果您正在使用包含许多列的文件,那么必须记住列名称的索引会令人抓狂。 I think for readability the DictReader wins. 我认为为了便于阅读,DictReader获胜。

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

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