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

Question:

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
Asked By: JSmooth

||

Answers:

If the CSV has headers, I would suggest using csv.DictReader. With this you can do:

 with open('C:/Python27/testweight.csv', 'rb') as f:
    reader = csv.DictReader(f)
    for row in reader:
        integer = int(row['Name of Column'])
Answered By: Jasper van den Berg

You could just iterate over all of the rows as follows:

import csv

with open('testweight.csv', newline='') as f:
    rows = list(csv.reader(f))      # Read all rows into a list

for row in rows[1:]:    # Skip the header row and convert first values to integers
    row[1] = int(row[1])

print(rows)

This would display:

[['Account', 'Value'], ['ABC', 6], ['DEF', 3], ['GHI', 4], ['JKL', 7]]

Note: your code is checking for > 's'. This would result in you not getting any rows as numbers would be seen as less than s. If you still use Python 2.x, change the newline='' to 'rb'.

Answered By: Martin Evans

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]
Answered By: martineau

count = 0 # Used to skip the first line, heading columns

with open(sys.argv[1], "r") as t:
reader = csv.reader(t) #Normal reader function

    for row in reader:
        if count > 0:
            teams.append({
                "key_one": row[0],
                "key_two": int(row[1]) #Convert the Value here
            })
        count += 1
Answered By: William Mabotja
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.