Python csv文本操作

2024-04-18 17:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将输入.csv文件中的combine字段合并到.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.writerwriterow(),但它在每个字符之间放置逗号分隔符。我尝试过定义一个escapechar,但它只输出“John\”,“Jr.”建议?在


Tags: 文件csvthe代码outputifpassopen
3条回答

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

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

csv.writer允许您add a ^{} keyword,它可以用来控制引用的方式。在

你可能想要一些类似csv.QUOTE_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'])

如果您想知道有关CSV的详细信息,有一个规范:http://tools.ietf.org/html/rfc4180

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

如果用双引号括起字段,则出现在字段内的双引号必须在其前面加上另一个双引号来转义

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

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

mcvs = csv.writer(open('file.csv', 'wb'), quoting=csv.QUOTE_ALL)

将始终在字段值周围添加引号。在

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

http://docs.python.org/library/csv.html#module-csv

相关问题 更多 >