Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string values to integer values while reading a CSV file?

When opening a CSV file, the column of integers is being converted to a string value ('1', '23', etc.). What's the best way to loop through to convert these back to integers?

import csv

with open('C:/Python27/testweight.csv', 'rb') as f:
    reader = csv.reader(f)
    rows = [row for row in reader if row[1] > 's']

for row in rows:
    print row

CSV file below:

Account Value
ABC      6
DEF      3
GHI      4
JKL      7
like image 313
JSmooth Avatar asked Nov 05 '15 14:11

JSmooth


People also ask

How do you convert a string to an integer 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 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

I think this does what you want:

import csv

with open('C:/Python27/testweight.csv', 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    header = next(reader)
    rows = [header] + [[row[0], int(row[1])] for row in reader if row]

for row in rows:
    print(row)

Output:

['Account', 'Value']
['ABC', 6]
['DEF', 3]
['GHI', 4]
['JKL', 7]
like image 117
martineau Avatar answered Oct 19 '22 10:10

martineau