python - 将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]...]
解决方案
@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
.
推荐阅读
- python - kaggle notebook 上 sqlalchemy 库的函数 create_engine().execute() 出错
- java - 在 Java 中将字符串分解为句子:BreakIterator 在第二次出现“Dr.”时失败。
- python - 如何告诉 CP-SAT 设置具有某些偏好的决策变量?
- flutter - 在 Flutter 的 TextPainter 中,文本颜色在调试和发布时有所不同
- typescript - 如何在带有打字稿的Vue中使用变量值作为占位符
- php - Codeigniter SQL Server [您在 config/database.php 文件中指定了无效的数据库连接组(默认)。]
- java - 根据给定的频率将日期拆分为相等的间隔
- rubygems - 在 cataline macos 上安装 therubyracer gem 时出错
- python - pandas dataframe - 如何找到满足某些条件的连续行?
- javascript - JavaScript - 将数组中的每 3 个项目包装到 div