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
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") .
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With