首页 > 解决方案 > 将csv文件读入列表并将字符串转换为整数Python

问题描述

我正在尝试读取 CSV 文件,然后将所有数据返回到列表中。我首先尝试csv.reader使用以下代码读取 csv 文件:

import csv
with open(fileName, 'r') as f:
    next(f)
    data = csv.reader(f)
    dataList = list(data)   

我现在有一个看起来像这样的列表:

[['123', '234', '456', '567']
['345', '3456', '5678', '678']
['2345', '4567', '45678', '56789']
...]

我注意到这些数字在列表中存储为字符串,所以我创建了一个新列表,newList = [int(i) for i in dataList]并收到此错误消息TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

所以我尝试了我在 Youtube 上看到的以下代码:

with open('fileName', 'r') as f:
    next(f)
    data = csv.reader(f)
    data_lst = []
    for line in reader:
        data_lst.append([int(line)])

我收到此错误消息:

ValueError                                Traceback (most recent call last)
<ipython-input-123-9fbefdb892ab> in <module>
      3     data = csv.reader(f)
      4     data_lst = []
----> 5     for line in reader:
      6         data_lst.append([int(line)])

ValueError: readline of closed file

有谁知道如何将列表中的字符串转换为整数?

非常感谢!

示例 csv 文件

    number1    number2    number3    number4
0    123        456        567        5678
1    4567       3456       6789       2345   
....

我需要阅读这个 csv 文件并将数据存储在一个列表中,以便 csv 文件中的每一行都是一个类似的列表[[123, 456, 567, 5678], [4567, 3456, 6789, 2345]...]

标签: pythonlistcsv

解决方案


@brunoto 提供的答案是正确的,我更喜欢这个解决方案(更接近你的):

with open('fileName', 'r') as f:
    next(f)
    data = csv.reader(f)
    data_lst = []
    for line in reader:
        data_lst.append([int(x) for x in line])

请注意,所需要的只是对最后一行进行更改,循环遍历每行的元素并将它们int单独转换,而不是尝试将整行(一条记录,即 a list)转换为单个int.


推荐阅读