【问题标题】:Fixing extra double-quotes in csv for string with double-quote at start and middle?修复csv中额外的双引号,用于在开头和中间带有双引号的字符串?
【发布时间】:2019-08-26 04:06:20
【问题描述】:

尝试将行写入 csv 文件。在字符串的开头和中间添加带有双引号的字符串时,当我以 .txt 格式打开它时会得到额外的双引号,但以 .xlsx 格式打开时没有问题。

我玩过 quoting=QUOTE_NONEquotechar='//'escapechar='//',但可以不知道什么是有效的。

代码如下:

import csv

csv_file = open('file.csv', 'w', newline='')
file_writer = csv.writer(csv_file)
file_writer.writerow(['Name', 'Search term'])

name = 'Patrick Fox'
search_term = '"%s" mp' % name
file_writer.writerow([name, search_term])

^ 问题在于 search_term。 .txt 和 .xlsx 的预期输出为 "Patrick Fox" mp。 .txt 的实际输出为 """Patrick Fox"" mp"

【问题讨论】:

    标签: python python-3.x csv escaping double-quotes


    【解决方案1】:

    我认为你不能,因为分隔符后的双引号将被视为 XLS 格式的特殊引用,阅读器不会显示它,但可以在原始格式(作为文本文件)中看到。 所以我认为你有两个选择:

    用单引号代替双引号:

    import csv
    
    csv_file = open('file.csv', 'w', newline='')
    file_writer = csv.writer(csv_file)
    file_writer.writerow(['Name', 'Search term'])
    
    name = 'Patrick Fox'
    search_term = '{!r} mp '.format(name)
    file_writer.writerow([name, search_term])
    

    另一种选择是在第二列中添加一个空格字符。另外,我将quoting 设置为None。您可以在here 中找到有关 CSV 格式的更多信息。

    import csv
    
    
    csv_file = open('file.csv', 'w', newline='')
    file_writer = csv.writer(
        csv_file, quoting=csv.QUOTE_NONE, quotechar='\\')
    file_writer.writerow(['Name', 'Search term'])
    
    name = 'Patrick Fox'
    search_term = ' \"{!s}\" mp '.format(name)
    file_writer.writerow([name, search_term])
    

    【讨论】:

    • 非常感谢!我使用了第二个选项,它有效。我不能使用第一个选项,因为我正在使用 search_term 变量来搜索网站上的确切短语。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2016-06-08
    • 2014-09-18
    • 2017-02-26
    • 2014-09-20
    相关资源
    最近更新 更多