Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中迭代CSV文件的困难_Python_Python 3.x_Csv - Fatal编程技术网

在Python中迭代CSV文件的困难

在Python中迭代CSV文件的困难,python,python-3.x,csv,Python,Python 3.x,Csv,我试图用Python将CSV文件中给定行中的所有值相加,但在这样做时遇到了一些困难 这是我最近的一次: from csv import reader with open("simpleData.csv") as file: csv_reader = reader(file) for row in csv_reader: total = 0 total = total + int(row[1]) print(total) 最终的pri

我试图用Python将CSV文件中给定行中的所有值相加,但在这样做时遇到了一些困难

这是我最近的一次:

    from csv import reader
with open("simpleData.csv") as file:
    csv_reader = reader(file)



    for row in csv_reader:
        total = 0
        total = total + int(row[1])
print(total)
最终的print语句不是生成第[1]行中所有值的总和,而是只生成该行中的最后一个数字。我在做什么

我还遇到了绕过标题的问题(我在其他示例中看到的广泛使用的next()似乎来自Python 2,并且该方法在P3中不再适用),所以我只是手动临时将该列的标题更改为0


任何帮助都将不胜感激。

似乎您在每次迭代中将
总计
变量重置为零

要解决此问题,请将变量初始化移到
for
循环的外部,使其仅发生一次:

total = 0
for row in csv_reader:
    total = total + int(row[1])

似乎每次迭代都要将
total
变量重置为零

要解决此问题,请将变量初始化移到
for
循环的外部,使其仅发生一次:

total = 0
for row in csv_reader:
    total = total + int(row[1])
  • 总计应移到for循环的外部
  • 缩进在Python中很重要。例如,导入行应推到最左侧
  • 总计应移到for循环的外部
  • 缩进在Python中很重要。例如,导入行应推到最左侧

  • 如果要重置总数,请尝试以下操作:

    from csv import reader
    with open("simpleData.csv") as file:
        csv_reader = reader(file)
    
        total = 0
    
        for row in csv_reader:
            total = total + int(row[1])
    print(total)
    

    如果要重置总数,请尝试以下操作:

    from csv import reader
    with open("simpleData.csv") as file:
        csv_reader = reader(file)
    
        total = 0
    
        for row in csv_reader:
            total = total + int(row[1])
    print(total)
    

    正如其他人已经指出的,您正在每次迭代中设置
    total
    的值。您可以将
    total=0
    移动到循环之外,或者使用:


    正如其他人已经指出的,您正在每次迭代中设置
    total
    的值。您可以将
    total=0
    移动到循环之外,或者使用:


    啊,非常感谢!这工作做得很好。我刚刚开始,来自JS,所以实际上,Python的缩进/缩进敏感性对我来说有点棘手。啊,非常感谢!这工作做得很好。我刚开始学习,来自JS,所以实际上,Python的缩进/缩进敏感性对我来说有点棘手。