代码之家  ›  专栏  ›  技术社区  ›  Iceland_jack

在python中循环遍历.csv文件中的列

  •  4
  • Iceland_jack  · 技术社区  · 16 年前

    我希望能够使用python打开 .csv 文件如下:

    5,26,42,2,1,6,6
    

    然后对它们执行一些操作,比如加法。

    total = 0
    with open("file.csv") as csv_file:
            for row in csv.reader(csv_file, delimiter=','):
                for number in range(7):
                    total += int(row[number]) 
    

    问题是因为 CSV 文件只有一行和未知的列数,我不知道如何在没有像这样硬编码或使用非常难看的代码的情况下使其工作。

    有什么方法可以用类似 for columns in file 用巨蟒?

    2 回复  |  直到 12 年前
        1
  •  8
  •   Eli Courtwright    16 年前

    你可以说

    for col in row:
        total += int(col)
    

    例如:

    import csv
    from StringIO import StringIO
    
    total = 0
    for row in csv.reader(StringIO("1,2,3,4")):
        for col in row:
            total += int(col)
    
    print total    # prints 10
    

    之所以可以这样做,是因为csv.reader为每一行返回一个简单的列表,所以您可以像在python中的任何其他列表一样对其进行迭代。

    但是,在您的例子中,由于您知道您有一个文件,其中包含一行逗号分隔的整数,因此您可以使这个过程简单得多:

    line = open("ints.txt").read().split(",")
    total = sum(int(i) for i in line)
    
        2
  •  3
  •   jcdyer Anand S Kumar    16 年前

    可以迭代列列表,就像在csv阅读器中迭代行一样:

    total = 0
    with open("file.csv") as csv_file:
       for row in csv.reader(csv_file, delimiter=','):
            for col in row:
                total += int(col)
    

    或者,您可以在每次传递中添加每行的总和,并跳过内部循环:

    total = 0
    with open("file.csv") as csv_file:
       for row in csv.reader(csv_file, delimiter=','):
            total += sum(map(int, row))
    

    或者,您可以使用 itertools.imap 而不是 map .