gpt4 book ai didi

python - 读取 CSV 文件并在数据项两边加上双引号

转载 作者:行者123 更新时间:2023-12-01 04:11:00 24 4
gpt4 key购买 nike

这是我的数据:

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"

最佳答案

您可以将整数字段转换为整数值,如下所示:

for row in reader:
row = [int(x) if re.match(r'-?\d+$', x) else x for x in row]
writer.writerow(row)

只需添加

import re

在程序的开头。

关于python - 读取 CSV 文件并在数据项两边加上双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com