How to check if a CSV has a header using Python?

前端 未结 5 559
再見小時候
再見小時候 2021-01-17 22:54

I have a CSV file and I want to check if the first row has only strings in it (ie a header). I\'m trying to avoid using any extras like pandas etc. I\'m thinking I\'ll use a

5条回答
  •  感情败类
    2021-01-17 23:45

    I'd do something like this:

    is_header = not any(cell.isdigit() for cell in csv_table[0])
    

    Given a CSV table csv_table, grab the top (zeroth) row. Iterate through the cells and check if they contain any pure digit strings. If so, it's not a header. Negate that with a not in front of the whole expression.

    Results:

    In [1]: not any(cell.isdigit() for cell in ['2','1'])
    Out[1]: False
    
    In [2]: not any(cell.isdigit() for cell in ['2','gravy'])
    Out[2]: False
    
    In [3]: not any(cell.isdigit() for cell in ['gravy','gravy'])
    Out[3]: True
    

提交回复
热议问题