Skip to content

Instantly share code, notes, and snippets.

@catichenor
Last active October 12, 2025 18:54
Show Gist options
  • Select an option

  • Save catichenor/f0b2b1367fc51e7b037d4426b0bdd193 to your computer and use it in GitHub Desktop.

Select an option

Save catichenor/f0b2b1367fc51e7b037d4426b0bdd193 to your computer and use it in GitHub Desktop.
Check CSV file for a header row, and detect the dialect.
import csv
input_csv_file = '/path/to/test_csvfile.csv'
with open(input_csv_file, 'rb') as csvfile: #`with open(input_csv_file, 'r') as csvfile:` for Python 3
csv_test_bytes = csvfile.read(1024) # Grab a sample of the CSV for format detection.
csvfile.seek(0) # Rewind
has_header = csv.Sniffer().has_header(csv_test_bytes) # Check to see if there's a header in the file.
dialect = csv.Sniffer().sniff(csv_test_bytes) # Check what kind of csv/tsv file we have.
inputreader = csv.reader(csvfile, dialect)
if has_header:
next(inputreader) # Skip the header if we have one.
for row in inputreader:
print(row)
@patelh2016

Copy link
Copy Markdown

Thank you! So much!

@catichenor

Copy link
Copy Markdown
Author

Thank you! ๐Ÿ˜Š

Glad this helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment