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

6 投票
2 回答
45307 浏览
提问于 2025-04-15 20:29

我想用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文件只有一行,但列的数量不确定,所以我不知道该怎么做,既不想写死代码,也不想写得太复杂。

有没有办法在Python中用类似for columns in file的方式来遍历这些列呢?

2 个回答

3

你可以像遍历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,这样就不需要额外创建一个列表了。

9

你可以直接这样写

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会为每一行返回一个简单的列表,所以你可以像处理其他列表一样去遍历它。

不过,在你的情况下,因为你知道你的文件里只有一行用逗号分隔的整数,所以你可以把这个过程简化很多:

line = open("ints.txt").read().split(",")
total = sum(int(i) for i in line)

撰写回答