gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:14:20 26 4
gpt4 key购买 nike

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

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

没有任何问题。问题是我想将文件作为字典打开。 csv.DictReader 类没有 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)

我尝试打开文件并仅加载某些字段,如果我事先修改文件,将 ; 替换为 , (我为此使用了 notepad++),则该字段有效 -但我想跳过这一部分并直接打开文件。

最佳答案

两者DictReaderDictWriter接受任意参数,包括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=";")

应该按预期工作。

关于python - 如何让 DictReader 打开以分号作为字段分隔符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55060565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com