Check if csv has header in python
Posted on 31 Aug, 2021
Consider the following csv data
1
id, name, editor
2
1, Bhupesh, NeoVim
3
2, Mark, VSCode
4
3, Jennifer, JetBrains
Copied!
1
1, Banana, 34
2
2, Apples, 5
3
3, Orange, 33
4
4, Mango, 12
Copied!
The csv.Sniffer class provides a method called has_header which return True if the first row appears to be a header
1
import csv
2
​
3
csv_with_header = """
4
id, name, editor
5
1, Bhupesh, NeoVim
6
2, Mark, VSCode
7
3, Jennifer, JetBrains
8
"""
9
​
10
csv_without_header = """
11
1, Banana, 34
12
2, Apples, 5
13
3, Orange, 33
14
4, Mango, 12
15
"""
16
​
17
def has_header(file):
18
with open(file, 'r') as csvfile:
19
sniffer = csv.Sniffer()
20
return sniffer.has_header(csvfile.read())
21
​
22
​
23
print(has_header('csv_with_header.csv'))
24
# true
25
print(has_header('csv_without_header.csv'))
26
# false
Copied!
Last modified 13d ago
Copy link