Using Python 3.4 and Im trying to import csv files with some containing commas, others containing semicolons, and other containing tabs as delimiters.
Is it possible to let python detect which proper delimiter to use? i have read the post on python: import csv file (delimiter “;” or “,”) but cannot get the appropriate result.
My code thus far:
import csv
class Data(object):
def __init__(self, csv_file):
self.raw_data = []
self.read(csv_file)
def read(self, csv_file):
with open(csv_file, newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(), delimiters=',;')
csvfile.seek(0)
f = csv.reader(csvfile, dialect)
for row in f:
self.raw_data.append(row)
print(self.raw_data)
mycsv = Data('comma_separate.csv')
comma_separate.csv contains:
afsfaf@faf.com, $161,321, True, 1
asafasf@fafa.net, $95.00, False, 3
adaafa3@aca.com, $952025, False, 3
Right now my output is:
['afsfaf@faf.com, $161,321, True, 1'], ['asafasf@fafa.net, $95.00, False, 3'], ['adaafa3@aca.com, $952025, False, 3']
My desired output is:
['afsfaf@faf.com', '$161,321', 'True', '1'], ['asafasf@fafa.net', '$95.00', 'False', '3'], ['adaafa3@aca.com', '$952025', 'False', '3']