简体   繁体   English

固定csv中多余的双引号,以便在字符串的开头和中间加上双引号吗?

[英]Fixing extra double-quotes in csv for string with double-quote at start and middle?

Trying to write lines to a csv file. 尝试将行写入csv文件。 When adding a string with double-quotes at the begining and in the middle of the string, I get extra double-qoutes when I open it as .txt but no problem when opened as .xlsx. 当在字符串的开头和中间添加带双引号的字符串时,以.txt打开它会得到额外的双引号,但以.xlsx打开时没有问题。

I've played around with quoting=QUOTE_NONE and quotechar='//' and escapechar='//' , but can't figure out what works. 我玩过quoting = QUOTE_NONEquotechar ='//'escapechar ='//' ,但是不知道什么可行

Here's the code: 这是代码:

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])

^ Issue is with the search_term . ^问题与search_term有关 Expected output is "Patrick Fox" mp for both .txt and .xlsx. .txt和.xlsx的预期输出均为“ Patrick Fox” mp Actual output is """Patrick Fox"" mp" for .txt 实际输出为.txt的““” Patrick Fox“” mp“

I think you can't because the double quotes after the delimiter would be considered as special quoting in XLS format and the reader won't show it but can be seen on the raw format (as a text file). 我认为您不能,因为定界符后的双引号将被视为XLS格式的特殊引号,并且读者不会显示它,但可以在原始格式(作为文本文件)上看到它。 So I think you have two options: 所以我认为您有两种选择:

Use single quotes instead of double quotes: 使用单引号而不是双引号:

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])

Another option is to add a single space character in the second column. 另一种选择是在第二列中添加一个空格字符。 Also, I set the quoting to None . 另外,我将quoting设置为None You can find more about CSV formatting in 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM