我希望能够使用 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
的方法来遍历列?
最佳答案
你可以说
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)
关于python - 在 Python 中循环遍历 .csv 文件中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2457193/