18

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
3
  • 5
    A minor nit: CSV files are text files, so it's wrong to think that integers are being conveted to strings. They are already strings. The problem your having is that you want them to be converted to integers. Commented Nov 5, 2015 at 16:27
  • @StevenRumbalski Except, doesn't the CSV format accommodate numeric values and numbers that should be treated as strings (by using a single-quote prefix, or enclosing the number in double-quotes)? Commented Dec 4, 2018 at 21:43
  • I am not sure that unquoted values are considered as numeric. Values are text, and you need to quote it to avoid miss-interpretation of a separation/new line character located inside value Commented Jun 2, 2020 at 21:53

4 Answers 4

11

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but that is giving me "IndexError: list index is out of range"
Do I have to specify the range, and if so, where?
Sounds like some of the rows in the real .CSV file don't contain two values. If that's the case, you could skip them by changing the end of the list comprehension to ...for row in reader if len(row) > 1].
5

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'])

4 Comments

Thanks, but I am getting a KeyError: 1
This means there is a fault in the csv, would you mind posting a little part of the csv with the header?
I put it in original question
The column you want to fetch needs to by typed as a string, so: integer = int(row['1']). Do not forget the quotes!!!
4

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'.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.