Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file has a CSV format with Python

Tags:

python

csv

Could someone provide an effective way to check if a file has CSV format using Python ?

like image 874
Joe Avatar asked Jun 06 '10 16:06

Joe


People also ask

How do you tell if a file is a CSV?

Count the number of commas in the file per line, there should normally be the same amount of commas on each line of the file for it to be a valid CSV file.

How do I know the format of a file in Python?

The general way of recognizing the type of file is by looking at its extension. But this isn't generally the case. This type of standard for recognizing file by associating an extension with a file type is enforced by some operating system families (predominantly Windows).

How would one check whether the data file is a CSV file which Python function can be used to do this?

DictReader() class can be used to read a CSV file as a dictionary.


1 Answers

You could try something like the following, but just because you get a dialect back from csv.Sniffer really won't be sufficient for guaranteeing you have a valid CSV document.

csv_fileh = open(somefile, 'rb') try:     dialect = csv.Sniffer().sniff(csv_fileh.read(1024))     # Perform various checks on the dialect (e.g., lineseparator,     # delimiter) to make sure it's sane      # Don't forget to reset the read position back to the start of     # the file before reading any entries.     csv_fileh.seek(0) except csv.Error:     # File appears not to be in CSV format; move along 
like image 101
gotgenes Avatar answered Oct 05 '22 03:10

gotgenes