'Auto-detect the delimiter in a CSV file using pd.read_csv

Is there a way for read_csv to auto-detect the delimiter? numpy's genfromtxt does this. My files have data with single space, double space and a tab as delimiters. genfromtext() solves it, but is slower than pandas' read_csv. Any ideas?



Solution 1:[1]

For better control, I use a python module called detect_delimiter from python projects. See https://pypi.org/project/detect-delimiter/ . It has been around for some time. As with all code, you should test with your interpreter prior to deployment. I have tested up to python version 3.8.5.

See code example below where the delimiter is automatically detected, and the var delimiter is defined from the method's output. The code then reads the CSV file with sep = delimiter. I have tested with the following delimiters, although others should work: ; , |

It does not work with multi-char delimiters, such as ","

CAUTION! This method will do nothing to detect a malformed CSV file. In the case where the input file contains both ; and , the method returns , as the detected delimiter.

from detect_delimiter import detect
import pandas as pd

delimiter = ''
with open(security_rule_file.csv) as myfile:
    firstline = myfile.readline()
    delimiter = detect(firstline)
    myfile.close()

records = pd.read_csv(security_rule_file.csv, sep = delimiter)

Solution 2:[2]

Another option is to use the built in CSV Sniffer. I mix it up with only reading a certain number of bytes in case the CSV file is large.

import csv

def get_delimiter(file_path, bytes = 4096):
    sniffer = csv.Sniffer()
    data = open(file_path, "r").read(bytes)
    delimiter = sniffer.sniff(data).delimiter
    return delimiter

Solution 3:[3]

You should return the validated data as the error said.

class TempDriverUserSerializer(serializers.ModelSerializer):
    class Meta:
        model=Tempdriver
        fields=('username','mobile')

    def validate_username(self,username):       
        user=Tempdriver.objects.filter(username=username)
        user_exists = AppUser.objects.filter(username=username)
        if  user.exists() and user_exists.exists():
            raise serializers.ValidationError("UserName already exists")
        return username

    def validate_mobile(self, mobile):
        mobile=Tempdriver.objects.filter(mobile=mobile)
        if mobile.exists():
            raise serializers.ValidationError("Mobile Number already exists")
        return mobile

Solution 4:[4]

you are not returning anything in validate. change your validate to

def validate(self,attrs):
    username = attrs.get('username')
    user=Tempdriver.objects.filter(username=username)
    user_exists = AppUser.objects.filter(username=username)
    if  user.exists() and user_exists.exists():
        raise serializers.ValidationError("UserName already exists")
    return attrs

also return mobile in your validate_mobile too

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Syed Muntazir Mehdi
Solution 2 pietz
Solution 3 Messaoud Zahi
Solution 4 Abdul Raffay