如何让 DictReader 打开一个以分号作为字段分隔符的文件?

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

我的 csv 文件以分号作为分隔符。我可以用

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

没有任何问题。问题是我想将文件作为字典打开。 csv.DictReader class 没有 delimiter 选项。

我的代码:

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)

我尝试打开文件并只加载某些字段,如果我事先修改文件,将 ; 替换为 ,(我为此使用记事本++),这会起作用——但我想跳过这部分,直接打开文件。

两者 DictReader and DictWriter 都接受包括 delimiter 在内的任意参数,并将它们传递给基础 readerwriter 对象,如文档所述:

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.

将上面代码中的相关行更改为

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

应该按预期工作。