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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33547790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:32:58  来源:igfitidea点击:

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

pythonstringloopscsvint

提问by JSmooth

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?

打开 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 file below:

CSV 文件如下:

Account Value
ABC      6
DEF      3
GHI      4
JKL      7

采纳答案by martineau

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

Output:

输出:

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

回答by Jasper van den Berg

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

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

回答by Martin Evans

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

您可以按如下方式遍历所有行:

import csv

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

for row in rows[1:]:         # Skip the header row
    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.

注意:您的代码正在检查> 's'. 这将导致您无法获得任何行,因为数字将被视为小于s