Last active
October 12, 2025 18:54
-
-
Save catichenor/f0b2b1367fc51e7b037d4426b0bdd193 to your computer and use it in GitHub Desktop.
Check CSV file for a header row, and detect the dialect.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Author
Thank you! ๐
Glad this helped!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! So much!