我希望能够使用Python打开这样的.csv文件:
5,26,42,2,1,6,6
Run Code Online (Sandbox Code Playgroud)
然后像添加一样对它们执行一些操作.
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])
Run Code Online (Sandbox Code Playgroud)
问题是,由于.csv文件只有一行和一个未知数量的列,我不知道如何使这个工作没有硬编码或使用真正丑陋的代码.
有没有办法使用像for columns in filePython 这样的东西循环遍历列?
你可以说
for col in row:
total += int(col)
Run Code Online (Sandbox Code Playgroud)
例如:
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
Run Code Online (Sandbox Code Playgroud)
您可以这样做的原因是csv.reader为每一行返回一个简单的列表,因此您可以像在Python中的任何其他列表一样迭代它.
但是,在您的情况下,由于您知道您的文件包含一行以逗号分隔的整数,因此您可以使这更简单:
line = open("ints.txt").read().split(",")
total = sum(int(i) for i in line)
Run Code Online (Sandbox Code Playgroud)