Python: skip comment lines marked with # in csv.DictReader

前端 未结 4 1610
旧时难觅i
旧时难觅i 2020-12-01 01:35

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 s         


        
4条回答
  •  执念已碎
    2020-12-01 02:08

    Just posting the bugfix from @sigvaldm's solution.

    def decomment(csvfile):
    for row in csvfile:
        raw = row.split('#')[0].strip()
        if raw: yield row
    
    with open('dummy.csv') as csvfile:
        reader = csv.reader(decomment(csvfile))
        for row in reader:
            print(row)
    

    A CSV line can contain "#" characters in quoted strings and is perfectly valid. The previous solution was cutting off strings containing '#' characters.

提交回复
热议问题