如何在读取CSV文件时将字符串值转换为整数值?

时间:2015-11-05 14:55:42

标签: python string loops csv int

打开CSV文件时,整数列将转换为字符串值(' 1',' 23'等)。循环将这些转换回整数的最佳方法是什么?

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文件:

Account Value
ABC      6
DEF      3
GHI      4
JKL      7

3 个答案:

答案 0 :(得分:6)

我认为这可以满足您的需求:

import csv

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

for row in rows:
    print row

输出:

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

答案 1 :(得分:2)

如果CSV包含标题,我建议您使用csv.DictReader。有了这个,你可以这样做:

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

答案 2 :(得分:0)

您可以按如下方式迭代所有行:

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 index, cols in enumerate(rows[1:], 1):  # Skip the header row
    rows[index][1] = int(cols[1])

print rows

这会显示:

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