读取CSV文件并在数据项周围加上双引号

2024-05-15 15:24:48 发布

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

以下是我的数据:

ID,application_id,award_notice_date,budget_start,budget_end,core_project_num,ed_inst_type 1,3000011,7/1/1985,6/30/1986,A03AH000859,SCHOOLS OF PUBLIC HEALTH 2,3000012,7/1/1985,6/30/1986,A03AH000860,SCHOOLS OF PUBLIC HEALTH 3,3000013,7/1/1985,6/30/1986,A03AH000861,SCHOOLS OF PUBLIC HEALTH

我想要的是:

"ID","application_id","budget_start","budget_end","core_project_num","ed_inst_type" 1,3000011,"7/1/1985","6/30/1986","A03AH000859","SCHOOLS OF PUBLIC HEALTH" 2,3000012,"7/1/1985","6/30/1986","A03AH000860","SCHOOLS OF PUBLIC HEALTH" 3,3000013,"7/1/1985","6/30/1986","A03AH000861","SCHOOLS OF PUBLIC HEALTH"

这是我的代码:

import csv

import sys


input_file = str(sys.argv[1])

output_file = str(sys.argv[2])


ifile  = open(input_file)

reader = csv.reader(ifile)

ofile  = open(output_file, 'w')

writer = csv.writer(ofile, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)

for row in reader:

       writer.writerow(row)

问题是: 为所有数据添加双引号(包括数字和非数字数据)

"ID","application_id","budget_start","budget_end","core_project_num","ed_inst_type" "1","3000011","7/1/1985","6/30/1986","A03AH000859","SCHOOLS OF PUBLIC HEALTH" "2","3000012","7/1/1985","6/30/1986","A03AH000860","SCHOOLS OF PUBLIC HEALTH" "3","3000013","7/1/1985","6/30/1986","","A03AH000861","SCHOOLS OF PUBLIC HEALTH"


Tags: ofcsv数据coreprojectidapplicationpublic