Python:跳过在csv.DictReader中用#标记的注释行 [英] Python: skip comment lines marked with # in csv.DictReader

查看:1384
本文介绍了Python:跳过在csv.DictReader中用#标记的注释行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 csv.DictReader 处理CSV文件非常棒 - 但我有CSV文件(例如:

Processing CSV files with csv.DictReader is great - but I have CSV files with comment lines in (indicated by a hash at the start of a line), for example:


# step size=1.61853
val0,val1,val2,hybridisation,temp,smattr
0.206895,0.797923,0.202077,0.631199,0.368801,0.311052,0.688948,0.597237,0.402763
-169.32,1,1.61853,2.04069e-92,1,0.000906546,0.999093,0.241356,0.758644,0.202382
# adaptation finished

csv模块不包括任何方式跳过这样的行

我可以轻松地做一些hacky,但我想象有一个很好的方法来包装一个csv.DicReader周围的其他迭代器对象,它的预处理,以丢弃行。

I could easily do something hacky, but I imagine there's a nice way to wrap a csv.DicReader around some other iterator object, which preprocesses to discard the lines.

推荐答案

使用过滤器可以很好地工作:

import csv
fp = open('samples.csv')
rdr = csv.DictReader(filter(lambda row: row[0]!='#', fp))
for row in rdr:
    print(row)
fp.close()

这篇关于Python:跳过在csv.DictReader中用#标记的注释行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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