Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv reader - convert string to int on the for line when iterating

Tags:

python

I'm interested in not having to write map the int function to the tuple of strings where I currently have it. See the last part of my example:

import os
import csv

filepath =  os.path.normpath("c:/temp/test.csv")

individualFile = open(filepath,'rb')
dialect = csv.Sniffer().sniff(individualFile.read(1000))

individualFile.seek(0)
reader = csv.reader(individualFile,dialect)

names = reader.next()

print names

def buildTree(arityList):
    if arityList == []:
        return 0            
    else:
        tree = {}
        for i in xrange(arityList[0][0],arityList[0][1]+1):
            tree[i] = buildTree(arityList[1:])
        return tree


census = buildTree([(1,12),(1,6),(1,4),(1,2),(0,85),(0,14)])

for m, f, s, g, a, c, t in reader:
    try:
        m,f,s,g,a,c,t = map(int,(m,f,s,g,a,c,t))
        census[m][f][s][g][a][c] += t
    except:
        print "error"
        print m, f, s, g, a, c, t
        break   

What I want to do is something like this:

for m, f, s, g, a, c, t in map(int,reader):
    try:
        census[m][f][s][g][a][c] += t
    except:
        print "error"
        print m, f, s, g, a, c, t
        break    

I try this and I get the following error:

TypeError: int() argument must be a string or a number, not 'list'

I'm having trouble understand this error message. I thought reader was an iterable object - not a list. It returns a list for each iteration, but it itself is not a list, correct? I guess that is more of a side question. What I really want to know is if there is a way to do what I am trying to do. Sorry for the code that doesn't really relate, but I thought I would include my whole example. Feel free to tear it to bits! :) I'm wondering if it might be better to just have one dict where the key is a tuple instead of this nested dictionary stuff, but even so, I'm still interested in figuring out my question.

like image 543
oob Avatar asked Sep 10 '10 04:09

oob


People also ask

How do you convert a string str to an int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

What happens if you convert string to int Python?

While converting from string to int you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers. Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int() function.

How do I read an integer from a csv file in Python?

Reading numbers in a CSV file with quotes: writerow() will quote all fields and the numbers will now be stored in quotes. To read the numbers from each row, we make use of the reader object from CSV library and store all the rows within a list 'output', which we would also print afterward.


1 Answers

what you want is something like:

def int_wrapper(reader):
    for v in reader:
        yield map(int, v)

Your code would then look like:

reader = csv.reader(individualFile,dialect)
reader = int_wrapper(reader)

# all that other stuff

for m, f, s, g, a, c, t in reader:
    try:
        census[m][f][s][g][a][c] += t
    except:
        print "error"
        print m, f, s, g, a, c, t
        break    

This is just using a generator function to wrap the reader and convert the input to integers.

The origin of the TypeError is that reader is a generator function which yields lists of values. When you apply map to it, you are applying map to a 'list' of lists. This is different than applying map to a list of values which you do when you write it out the long way.

For illustration, another way to do it is

for m, f, s, g, a, c, t in (map(int, v) for v in reader):
    # code

This just uses an in situ generator expression instead of defining a function. It's a matter of taste.

like image 122
aaronasterling Avatar answered Oct 01 '22 18:10

aaronasterling