Search code examples
pythondialect

Is it possible to use different dialects on different fields?


I am reading CSV file with python and for some fields I want to remove escape char ('aaa/bb' to aaabb) and for some fields leave it without a change.

for example: input:13,0,0,"0",false,"test\\file",-1,-1,1314570610162,13,"1","Danny","name\\Mary"
expected output:13,0,0,"0",false,"testfile",-1,-1,1314570610162,13 ,"1","Danny","name\Mary"

This is the code I am using:

csv.register_dialect('mydialect', escapechar='\\')
dialect = csv.get_dialect('mydialect')
writer = csv.writer(sys.stdout, dialect=dialect)
writer.writerow
(
    (
        <row to write>
    )
)

Can I use several dialects on the same row? how? another idea?


Solution

  • You're overthinking it. You don't need to have multiple dialects, they describe the csv file layout. You want to remove characters within certain fields, which is easily done before writing your output.

    Something like this should be good:

    reader = csv.reader(yourFileHandle)
    writer = csv.writer(outputFileHandle)
    for row in reader:
        row[5] = row[5].replace(r'\','')
        writer.writerow(row)