1

Here is my data:

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

What I want is:

"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"

Here is my code:

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)

The issue: Add double quotes for all data (including both numeric and non-numeric data)

"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"

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
FU USF
  • 25
  • 2
  • 8
  • 2
    Duplicate of http://stackoverflow.com/a/9354366/5818240. Make sure your numeric data are not read as strings. – JD Forster Jan 22 '16 at 22:38
  • Possible duplicate of [Python CSV module - quotes go missing](http://stackoverflow.com/questions/9353792/python-csv-module-quotes-go-missing) – WorldSEnder Jan 23 '16 at 00:02

1 Answers1

2

You can convert the integer fields to integer values with something like this:

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

just add

import re

at the beginning of your program.

Jacques Supcik
  • 619
  • 3
  • 8