pythonexcelpython-3.xcsvbank

How can I make DictReader open a file with a semicolon as the field delimiter?


My csv file has the semicolon as delimiter. I can open it with

r = csv.reader(infile, delimiter=";")

without any issues. The problem is that I want to open the file as a dict. The csv.DictReader class doesn't have the delimiter option.

My code:

import os
import csv
fields = ["Buchungstag", "Buchungstext", "Beguenstigter/Zahlungspflichtiger", "", "", "Betrag", "Verwendungszweck"]

with open("bank.csv") as infile, open("temp2.csv", "w", newline="") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, fields, extrasaction="ignore")
    w.writeheader()
    for row in r:
        w.writerow(row)

I tried opening the file and only loading certain fields, which works if I modify the file beforehand, replacing the ; with , (I used notepad++ for this) – but I would like to skip this part and have the file directly opened.


Solution

  • Both DictReader and DictWriter accept arbitrary arguments including delimiter, and pass them through to the underlying reader or writer object, as the documentation says:

    class csv.DictReader(…)

    All other optional or keyword arguments are passed to the underlying reader instance.

    class csv.DictWriter(…)

    Any other optional or keyword arguments are passed to the underlying writer instance.

    Changing the relevant line in your code above to

        r = csv.DictReader(infile, delimiter=";")
    

    should work as expected.