Read in Python with csv.reader a file with two different delimiter in the same file

I want to import a file from MySQL to python but there are two type of delimiters in the same file, on the same line.

For example:

FIELDA_FIELDB_FIELDC; FILEDD; FIELDE; FIELDF

I can split with _ or ; but cant find how to do both.

I have tried

csv_data = csv.reader(csvfile, delimiter=';' and '_')
csv_data = csv.reader(csvfile, delimiter=';' or'_')

I have also tried using csv.sniffer.

But only one delimiter is used each time.

How should i do ?

Answers


CSV files can only have one delimiter, so your approach can't work. If you can't fix the broken file, you can read it in two steps (assuming Python 2):

csv_data = []
with open("file.csv", "rb") as csvfile:
    reader = csv.reader(csvfile, delimiter=";")
    for row in reader:
        new = []
        for item in row:
            new.extend(item.split("_"))
        csv_data.append(new)

That solution is of course naive to things like escaped _ delimiters etc., but it might work as intended for you.


Need Your Help

SYSTEM_ALERT_WINDOW option greyed out (not changeable)

android permissions system-alert-window

I'm working on an App that is uses the SYSTEM_ALERT_WINDOW permission. I've added the permission to the Manifest.

Qt Meta System Call constructor with parameters

qt qtcore

I know that I can use QMetaType to create an object without parameters.