Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python写入csv忽略逗号_Python_Csv - Fatal编程技术网

Python写入csv忽略逗号

Python写入csv忽略逗号,python,csv,Python,Csv,我正在向csv写入数据,效果很好,但有些行的名称中有逗号,当我向csv写入数据时,这些逗号会将字段去掉……如何写入csv并忽略行中的逗号 header = "Id, FACID, County, \n" row = "{},{},{}\n".format(label2,facidcsv,County) with open('example.csv', 'a') as wildcsv: if z==0: wildcsv.write(header) wildc

我正在向csv写入数据,效果很好,但有些行的名称中有逗号,当我向csv写入数据时,这些逗号会将字段去掉……如何写入csv并忽略行中的逗号

header = "Id, FACID, County, \n"
row = "{},{},{}\n".format(label2,facidcsv,County)
with open('example.csv', 'a') as wildcsv:
    if z==0:
        wildcsv.write(header)
        wildcsv.write(row)
    else:
         wildcsv.write(row)

从写入行的每个字段中去掉任何逗号,例如:

label2 = ''.join(label2.split(','))
facidcsv = ''.join(facidcsv.split(','))
County = ''.join(County.split(','))
row = "{},{},{}\n".format(label2,facidcsv,County)
要对包含任意数量字段的行进行格式化,请执行以下操作:

def format_row(*fields):
    row = ''
    for field in fields:
        if row:
            row = row + ', ' + ''.join(field.split(','))
        else:
            row = ''.join(field.split(','))
    return row

label2 = 'label2, label2'
facidcsv = 'facidcsv'
county = 'county, county'
print(format_row(label2, facidcsv, county))
wildcsv.write(format_row(label2, facidcsv, county))
输出

正如@TomaszPlaskota和@quapka在评论中所提到的,Python的csv编写器和读取器默认情况下会写入/读取csv字段,这些字段包含一个带周围“”的分隔符。大多数使用csv文件的应用程序都采用相同的格式。因此,如果要在输出字段中保留逗号,以下是首选方法:

import csv

label2 = 'label2, label2'
facidcsv = 'facidccv'
county = 'county, county'
with open('out.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow((label2, facidcsv, county))
out.csv


你应该像这里展示的那样用双引号括起来:-row=\{},{},{}\.formatlabel2,facidcsv,CountyWhat about module?嗯,好的,这可以工作了-我有大约20多个字段要写,但问题中没有包括这些,有没有办法在所有列和行上删除大量逗号?
import csv

label2 = 'label2, label2'
facidcsv = 'facidccv'
county = 'county, county'
with open('out.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow((label2, facidcsv, county))
"label2, label2",facidccv,"county, county"