I want to check for an existing header in a newly created csv-file with the csv.Sniffer(). But I always get the same error:
:_csv.Error: Could not determine delimiter
The Code:
import csv
with open('example.csv', 'w') as csvfile:
print("file created")
with open('example.csv', 'r') as check_header_file:
has_header = csv.Sniffer().has_header(check_header_file.read(1024))
I've already tried to increase the size from 1024 to 2048 and to 3072.And I i tried to open the csv in 'rb' mode instead of only 'r'. For those who are interestet in the complete Traceback Call:
Traceback (most recent call last):
File "c:/Users/USER/Documents/Hobby/Test.py", line 6, in <module>
has_header = csv.Sniffer().has_header(check_header_file.read(1024))
File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\csv.py", line 393, in has_header
rdr = reader(StringIO(sample), self.sniff(sample))
File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\csv.py", line 187, in sniff
raise Error("Could not determine delimiter")
_csv.Error: Could not determine delimiter
And some pictures of the empty .csv where I'm trying to read the headers from


You can't check an empty .csv file with the python csv Sniffer. So I Tried a different approach with try and except. My Solution:
First you check with try if a file already exists or has Headers. And in except will the file or the Header created, if none exists