Python 3.4 import csv separator

Using Python 3.4 and Im trying to import csv files with some commas, others with a semicolon and others containing tabs as delimiters.

Is it possible for python to find out which correct delimiter to use? I read a post in python: imports a csv file (delimiter ";" or ",") , but cannot get the corresponding result.

My code is:

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

Now my conclusion:

['afsfaf@faf.com, $161,321, True, 1'], ['asafasf@fafa.net, $95.00, False, 3'], ['adaafa3@aca.com, $952025, False, 3']

My desired result:

['afsfaf@faf.com', '$161,321', 'True', '1'], ['asafasf@fafa.net', '$95.00', 'False', '3'], ['adaafa3@aca.com', '$952025', 'False', '3']
+4
source share
2 answers

csv , . , , :

afsfaf@faf.com, $161.321, True, 1

, , csv .

+1

sniff

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())
                csvfile.seek(0)
                f = csv.reader(csvfile, dialect)
                for row in f:
                   self.raw_data.append(row)

                print(csvfile.name)
                print(self.raw_data)


for f in ['tab_separate.tsv','comma_separate.csv','comma_separate2.csv']:
    mycsv = Data(f)

tab_separate.tsv
[['afsfaf@faf.com', '$161,321', 'True', '1'], ['asafasf@fafa.net', '$95.00', 'False', '3'], ['adaafa3@aca.com', '$952025', 'False', '3']]
comma_separate.csv
[['afsfaf@faf.com,', '$161,321,', 'True,', '1'], ['asafasf@fafa.net,', '$95.00,', 'False,', '3'], ['adaafa3@aca.com,', '$952025,', 'False,', '3']]
comma_separate2.csv
[['afsfaf@faf.com', '$161,321', 'True', '1'], ['asafasf@fafa.ne', '$95.00', 'False', '3'], ['adaafa3@aca.com', '$952025', 'False', '3']]

afsfaf@faf.com, $161,321, True, 1
asafasf@fafa.net, $95.00, False, 3
adaafa3@aca.com, $952025, False, 3

afsfaf@faf.com  $161,321    True    1
asafasf@fafa.net    $95.00  False   3
adaafa3@aca.com $952025 False   3

afsfaf@faf.com;$161,321;True;1
asafasf@fafa.ne;$95.00;False;3
adaafa3@aca.com;$952025;False;3
0

Source: https://habr.com/ru/post/1606748/


All Articles