Python:使用csv.writer,其中某些值可以包含“,”

时间:2018-01-25 18:20:38

标签: python csv

我正在使用csv.writer写入csv。

csv_writer = csv.writer( f , quotechar = '"' ,  quoting=csv.QUOTE_ALL )
csv_writer.writerow( header )

for row in rows :
   csv_writer.writerow([ row["value1"], row["value2"],row["value3"] ] )

但是我的一些值2就像这个名称,withcomma

所以在这些行中我最终得到了4列。

我尝试改为:

csv_writer = csv.writer( f , quotechar = '"' , delimiter = "|",  quoting=csv.QUOTE_ALL )

或我在chr(255)等数据上不存在的字符,但这完全搞砸了我的数据。

有什么想法吗?

更新

4列我的意思是对于具有该值的行,我看到:

column 2 : "Name
column 3 : withcomma"

而不是单个列"Name,withcomma“(并且第3列转移到第4列)

2 个答案:

答案 0 :(得分:1)

假设您的csv.writer([ row["value1"], row["value2"],row["value3"] ] )行不是拼写错误,它甚至不应该正常工作,因为您应该引用回csv_writer对象。请尝试使用csv_writer.writerow()代替

import csv
headers = ["col1", "col2", "col3"]
rows=[
    {"value1": "abc", "value2": "def", "value3": "FN,LN"},
    {"value1": "ghi", "value2": "jkl", "value3": "SN"}
]

with open('test.csv','w') as file:
    csv_writer = csv.writer(file,lineterminator="\n", quotechar = '"' ,  quoting=csv.QUOTE_ALL)
    csv_writer.writerow(headers)
    for row in rows:
        csv_writer.writerow([row["value1"],row["value2"],row["value3"]])

<强>输出:

"col1","col2","col3"
"abc","def","FN,LN"
"ghi","jkl","SN"

答案 1 :(得分:0)

实际上,您的示例代码csv.writer([ row["value1"], row["value2"],row["value3"]])(添加了缺少的尾部括号])会引发TypeError。见https://docs.python.org/3.5/library/csv.html?highlight=csv#csv.writer

从处理rows变量的方式来看,我认为它是一个dicts列表......如果这些数据准确无误,那么应该没有问题。这是一个工作示例代码

import csv
rows = [
    {"value1": "ab", "value2": "cd", "value3": "ef"},
    {"value1": "a,b", "value2": "cd", "value3": "ef"},
]
header = ["Name1", "Name2", "Name3"]
with open('output.csv', 'wb') as f:
    csv_writer = csv.writer(f , quotechar = '"' ,  quoting=csv.QUOTE_ALL )
    csv_writer.writerow( header )

    for row in rows:
        csv_writer.writerow([row["value1"], row["value2"], row["value3"]])

这给出了输出

"Name1","Name2","Name3"
"ab","cd","ef"
"a,b","cd","ef"