2016-01-22 36 views
1

這裏是我的數據:閱讀CSV文件,並把各地的數據項雙引號

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,公共衛生學校 2,3000012,7/1/1985,6/30/1986,A03AH000860,公共衛生學校 3,3000013,7/1/1985,6/30/1986 ,A03AH000861,公衆衛生學校

我要的是:

「ID」,「application_id」,「budget_start」,「budget_end」,「core_project_num」,「ed_inst_type」 1,3000011,「7/1/1985」,「6/30/1986」,「A03AH000859 「,」公共衛生學院「 2,3000012,」7/1/1985「,」6/30/1986「,」A03AH000860「,」公共衛生學院「 3,3000013,」7/1/1985 」, 「1986年6月30日」, 「A03AH000861」, 「公共健康」 學校

這裏是我的代碼:

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) 

問題: 添加雙引號的所有數據(包括雙方umeric和非數字數據)

「ID」, 「APPLICATION_ID」, 「budget_start」, 「budget_end」, 「core_project_num」, 「ed_inst_type」 「1」, 「3000011」,「7/1/1985年6月30日「A03AH000859」「公共衛生學院」 「2」,「3000012」,「7/1/1985」,「6/30/1986」,「A03AH000860」, 「3」, 「3000013」, 「公共衛生學校」, 「1985年7月1日」, 「1986年6月30日」, 「」, 「A03AH000861」, 「公共健康」 學校

+2

http://stackoverflow.com/a/9354366/5818240的副本。確保您的數字數據不被讀爲字符串。 –

+0

[Python CSV模塊 - 引號丟失]的可能重複(http://stackoverflow.com/questions/9353792/python-csv-module-quotes-go-missing) – WorldSEnder

回答

2

你可以用這樣的東西將整數字段轉換爲整數值:

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

只需添加

import re 

在程序的開始。