csv writer 两次向 python 添加双引号

问题描述 投票:0回答:1

我编写了一个 py 脚本,它接受 csv 文件,验证并更正它。问题是结果并不如预期。固定文件的结果内容有额外的双引号而不是单引号。有什么建议如何解决这个问题吗?以下是片段:

import csv

def process_csv():
    fixed_file_path = "C:\\files\\testing\\testing.csv"
    with open(fixed_file_path, mode="w", encoding="utf-8", newline='') as fixed_file:
        writer = csv.writer(fixed_file, delimiter=";")
        row = 'Path 2;"my text";red;2024-04-02T04:04:49;'
        writer.writerow([row])


if __name__ == "__main__":
    process_csv()

输出如下所示:“Path 2;”“my text””;red;2024-04-02T04:04:49;”

为什么要在“我的文本”中添加额外的双引号?

我尝试使用

quoting=csv.QUOTE_NONE, quotechar=None, escapechar=None
但随后收到一条错误消息:_csv.Error: need to escape, but no escapechar set

我使用的是python版本3.11.3

python csv
1个回答
-1
投票

我希望我正确理解了您的问题,并且这个答案能够解决您的问题。否则,请通过更多示例提供更清晰的解释。 将 process_csv 方法更改为:

def process_csv():
    fixed_file_path = "C:\\files\\testing\\testing.csv"
    with open(fixed_file_path, mode="w", encoding="utf-8", newline='') as fixed_file:
        writer = csv.writer(fixed_file, delimiter=";")
        row = 'Path 2;my text;red;2024-04-02T04:04:49;'
        writer.writerow([row])

[我的文本]不需要加双引号。

© www.soinside.com 2019 - 2024. All rights reserved.