Python csv文本操作

Python csv文本操作,python,csv,comma,Python,Csv,Comma,我想将输入.csv文件中的字段合并为输出到.csv文件,有些字段包含逗号。这是我的代码,简化了 outfile = open('output.csv', 'w') #these values are made up for this example; normally they would be read from #a csv and passed to the following 'combine()' function a = "John" b = ",Jr." def co

我想将输入.csv文件中的字段合并为输出到.csv文件,有些字段包含逗号。这是我的代码,简化了

outfile = open('output.csv', 'w')

#these values are made up for this example; normally they would be read from
#a csv and passed to the following 'combine()' function

a = "John"  
b = ",Jr."  

def combine(a, b):  
    if a == "":  
        pass  #don't write anything if the field is empty
    else:  
        outfile.write(a)  
    if b =="":  
        pass  
    else:  
        outfile.write(b)  
如果b以逗号开头,如何生成输出“John,Jr.”?我尝试过使用csv.writer writerow(),但它在每个字符之间放置了一个逗号分隔符。我曾尝试定义一个
escapechar
,但它只输出“John\”和“Jr.”建议?

csv.writer writerow()
需要一个值列表:

foo.writerow(['John', ',Jr.'])

如果您想继续使用纯Python:

resultStr = a+b
if ',' in resultStr: resultStr= '"' + resultStr + '"'

如果您想了解CSV的详细信息,有一个规范:

总的来说,它说明了以下几点: 包含换行符(CRLF)、双引号和逗号的字段应该用双引号括起来

如果用双引号括起字段,则字段中出现的双引号必须用另一个双引号进行转义

像Excel这样的实现总是将所有字段值放在双引号中

如果打开文件进行读或写操作,可以直接指定引用类型

mcvs = csv.writer(open('file.csv', 'wb'), quoting=csv.QUOTE_ALL)
将始终在字段值周围添加引号

有关所有可能的值,请参阅python文档


csv.writer
允许您选择可用于控制引用内容方式的内容

您可能需要类似于
csv.QUOTE\u MINIMAL
的内容

>>> import csv
>>> with open('eggs.csv', 'wb') as outfile:
...     writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL)
...     writer.writerow(['Spam'] * 5 + ['Baked Beans'])
...     writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

我通过在整个“name”输出字段周围手动双引号解决了这个问题。我更喜欢这个,因为它使我的代码更可读。非常感谢。这与我使用的解决方案非常相似。我将重写脚本,指定引用上面sebs帖子中提到的所有内容。