python - 如何在 python 中循环遍历 .csv 文件

标签 python dataframe for-loop iterator append

我正在尝试遍历 .csv 文件以便读取每一行,但我收到以下错误:

AttributeError: '_io.TextIOWrapper' 对象没有属性 'iterrows'

到目前为止,这是我的代码:

def i_list(input_file):

    input_list = []
    file = open(input_file, 'r')
    for i, j in file.iterrows():
            num1 = j[1]
            num2 = j[2]
            input_list.append(num1)
            input_list.append(num2)

i_list('nums.csv')

最佳答案

您可以使用 csv library

import reader from csv

input_list=[]
f = reader(open(input_file))
header = next(f) # if there is a header
for num1, num2 in f:
    input_list.append(num1)
    input_list.append(num2)

关于python - 如何在 python 中循环遍历 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57363725/

相关文章:

python - 从 python 数据框的列构造二分图

python - 如何在 Python 中向量化这个 for 循环?

javascript - 用循环填满我的双手

testing - 使用给定目录的输入运行特定程序的脚本

python - 为需要 30 分钟执行的脚本制作 Web 界面

python - Django 多项选择字段/复选框选择多个

python - 如何在索引中应用 value_counts 并创建新的数据帧?

python - pickle 多个字典

python - Mako 模板中重复使用的变量导致 "UnboundLocalError: local variable ' xyz' 在赋值之前被引用”

python - 无论如何,有没有办法取消分组 Pandas 数据框中的数据分组?