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

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

问题描述

使用 csv.DictReader 处理 CSV 文件非常棒- 但我有带有注释行的 CSV 文件(在行首用散列表示),例如:

Processing CSV files with csv.DictReader is great - but I have CSV files with comment lines (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.DictReader 包裹在其他一些迭代器对象周围,该对象进行预处理以丢弃行.

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

推荐答案

实际上这与 filter 配合得很好:

Actually this works nicely with filter:

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天全站免登陆