如何在读取CSV文件时将字符串值转换为整数值? [英] How to convert string values to integer values while reading a CSV file?
本文介绍了如何在读取CSV文件时将字符串值转换为整数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
打开CSV文件时,整数列将转换为字符串值(1,23等)。循环将这些转换回整数的最佳方法是什么?
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文件:
Account Value
ABC 6
DEF 3
GHI 4
JKL 7
推荐答案
我认为这样做你想要的:
I think this does what you want:
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]
这篇关于如何在读取CSV文件时将字符串值转换为整数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文