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 an if statement like if row[0] is a string print this is a CSV but I don't really know how to do that :-S any suggestions?
has_header = csv. Sniffer(). has_header(csv_test_bytes) # Check to see if there's a header in the file.
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.
A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file.
For files that are not necessarily in '.csv' format, this is very useful:
built-in function in Python to check Header in a Text file
def check_header(filename):
with open(filename) as f:
first = f.read(1)
return first not in '.-0123456789'
Answer by: https://stackoverflow.com/users/908494/abarnert
Post link: https://stackoverflow.com/a/15671103/7763184
Python has a built in CSV module that could help. E.g.
import csv
with open('example.csv', 'rb') as csvfile:
sniffer = csv.Sniffer()
has_header = sniffer.has_header(csvfile.read(2048))
csvfile.seek(0)
# ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With