Read inputfile as csv in python -


i want read csv file stdin , operate on it.

the following code reading csv file , doing operation needed. works fine. want take input stdin.

import csv open('hospital_data.csv', 'rb') csvfile:     mydict = {}      csvreader = csv.reader(csvfile, delimiter=',')     row in csvreader:         if row[6] not in mydict.keys():             #print 'zipcode: ' + row[6] + ' hospital code: ' + row[1]             mydict[row[6]] = 1         elif row[6] in mydict.keys():             #print 'value in row '+ str(mydict[row[6]])             mydict[row[6]] += 1 

is there way in python read file stdin csv file ?

csv.reader take yields lines, can use of methods shown @ answer lines stdin: how read stdin in python?

i'm partial fileinput myself due flexibility. eg:

import csv import fileinput  mydict = {} csvreader = csv.reader(fileinput.input(mode='rb'), delimiter=',') 

but works too:

import csv import sys  mydict = {} csvreader = csv.reader(sys.stdin, delimiter=',') 

if that, you'll want run -u command line argument make stream binary, if makes difference on platform: https://docs.python.org/2/using/cmdline.html#cmdoption-u

in either case you'll need use control-d mark end of input.

note correct way check if key in dict if row[6] in mydict rather checking keys. , in fact if want default value when key not present, use get:

for row in csvreader:     mydict[row[6]] = mydict.get(row[6], 0) + 1 

or collections.counter, since you're on 2.7:

mydict = collections.counter(row[6] row in csvreader) 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -