我试图用csv模块将每个字段值括在双引号中。但这里的诀窍是,在需要跳过的值之间有逗号。这是我用来将值括在引号中的片段。
数据:
col1,col2
first row,This section of the badge focuses on Communications
second row,Feedback has partnered with team members, leaders, and executives receive confidential, anonymous feedback代码段
import csv
with open('data.csv') as input, open('out.csv','w') as output:
reader = csv.reader(input)
writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
for line in reader:
writer.writerow(line)输出
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members"," leaders"," and executives receive confidential"," anonymous feedback"预期产出
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members, leaders, and executives receive confidential, anonymous feedback"发布于 2021-12-27 13:40:32
由于输入数据不是常规的CSV文件,使用csv模块读取输入文件可能会出现问题。为了解决这个问题,您可以直接读取文件的行,然后按如下方式解析它们:
import csv
with open('data.csv') as fin, open('out.csv','w') as fout:
writer = csv.writer(fout, delimiter=',', quoting=csv.QUOTE_ALL)
for line in fin:
writer.writerow(line.rstrip().split(',', 1))发布于 2021-12-27 13:42:10
您可以将DictReader和DictWriter与restkey属性一起使用:
with open('data.csv') as inp, open('out.csv', 'w') as out:
reader = csv.DictReader(inp, restkey='colN')
writer = csv.DictWriter(out, fieldnames=reader.fieldnames,
delimiter=',', quoting=csv.QUOTE_ALL)
writer.writeheader()
for line in reader:
line[reader.fieldnames[-1]] += ','.join(line.pop('colN', []))
writer.writerow(line)out.csv含量
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members leaders, and executives receive confidential, anonymous feedback"https://stackoverflow.com/questions/70495932
复制相似问题