Answer a question

There is a weird .csv file, something like:

header1,header2,header3
val11,val12,val13
val21,val22,val23
val31,val32,val33

pretty fine, but after these lines, there is always a blank line followed by lots of useless lines. The whole stuff is something line:


header1,header2,header3
val11,val12,val13
val21,val22,val23
val31,val32,val33

dhjsakfjkldsa
fasdfggfhjhgsdfgds
gsdgffsdgfdgsdfgs
gsdfdgsg

The number of lines in the bottom is totally random, the only remark is the empty line before them.

Pandas has a parameter "skipfooter" for ignoring a known number of rows in the footer.

Any idea about how to ignore this rows without actually opening (open()...) the file and removing them?

Answers

If you're using the csv module, it's fairly trivial to detect an empty row.

import csv 

with open(filename, newline='') as f:
    r = csv.reader(f)
    for l in r:
        if not l:
            break
        #Otherwise, process data
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐