简体   繁体   English

如何在Python的CSV文件中保留引号?

[英]How to keep quotes in CSV-Files in Python?

Hello there, 你好,

I have a problem with correct quotes when writing a CSV. 编写CSV时,引号有问题。 I want to write a CSV file with the built-in Python-CSV-library. 我想使用内置的Python-CSV库编写CSV文件。 My code is the following: 我的代码如下:

with open('test.csv', mode = 'w', newline = '') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter = ',', escapechar = '"', quoting = csv.QUOTE_NONE)

    csv_writer.writerow(['1', ' 0', ' Maker', ' "Tamas Nemes"'])
    csv_writer.writerow(['2', ' 0', ' Title', ' "A CSV file"'])

I tried many different parameter settings for the writer, but I always end up with this: 我为writer尝试了许多不同的参数设置,但最终总是这样:

1, 0, Maker, ""Tamas Nemes""
2, 0, Title, ""A CSV file""

Is there a way to get it like this: 有没有办法得到这样的:

1, 0, Maker, "Tamas Nemes"
2, 0, Title, "A CSV file"

Thanks for your help in advance! 谢谢您的帮助!

What you're trying to create isn't standard CSV format. 您尝试创建的不是标准CSV格式。 You can simply join all the strings and write that. 您可以简单地连接所有字符串并将其编写。

with open('test.csv', mode = 'w', newline = '') as csv_file:
    csv_file.write(",".join(['1', ' 0', ' Maker', ' "Tamas Nemes"']) + "\n")
    csv_file.write(",".join(['2', ' 0', ' Title', ' "A CSV file"']) + "\n")

I'm not able to comment and I agree with @CharlesDuffy your kind of abusing the CSV format. 我无法发表评论,我同意@CharlesDuffy那种滥用CSV格式的情况。

But you can get close to what you want by setting Escape Character to space (" ") 但是您可以通过将转义字符设置为空格(“”)来接近所需的内容

This will result in: 这将导致:

1,  0,  Maker, "Tamas  Nemes "
2,  0,  Title, "A  CSV  file "

Your strings are padded with extra spaces, but depending on what you need to do with them that might not matter. 您的字符串会被多余的空格填充,但这取决于您需要如何处理它们,这可能并不重要。

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

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