I have to convert some txt files to csv (and make some operation during the conversion).
I use csv.Sniffer() class to detect wich delimiter is used in the txt
This code
with open(filename_input, 'r') as f1, open(filename_output, 'wb') as f2:dialect = csv.Sniffer().sniff(f1.read(1024)) #### detect delimiters f1.seek(0)r=csv.reader(f1, delimiter=dialect )writer = csv.writer(f2,delimiter=';')
return: Error: Could not determine delimiter
This work
with open(filename_input, 'r') as f1, open(filename_output, 'wb') as f2:#dialect = csv.Sniffer().sniff(f1.read(1024)) #### detect delimiters #f1.seek(0)r=csv.reader(f1, delimiter='\t' )writer = csv.writer(f2,delimiter=';')
or
with open(filename_input, 'r') as f1, open(filename_output, 'wb') as f2:#dialect = csv.Sniffer().sniff(f1.read(1024)) #### detect delimiters #f1.seek(0)r=csv.reader(f1, dialect="excel-tab")writer = csv.writer(f2,delimiter=';')
this is a txt row example (10 records delimited by Tab)
166 14908941 sa_s NOVA i 7.05 DEa 7.17 Ncava - Deo mo 7161 4,97
why csv.Sniffer() class doesn't work?
The bug was read only 1024 byte to parse the entire txt(maybe this is not enough to detect the delimiter). Now this code works without no other edit:
with open(filename_input, 'r') as f1, open(filename_output, 'wb') as f2:dialect = csv.Sniffer().sniff(f1.read()) #### error with dialect = csv.Sniffer().sniff(f1.read(1024)) f1.seek(0)r=csv.reader(f1, delimiter=dialect )writer = csv.writer(f2,delimiter=';')