在Fi中访问和聚合特定列时出现问题

2024-06-14 06:00:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要访问一个.txt文件,并使用累加模式将最后所有列中的整数相加。我知道我已经正确地访问并打开了文件,但是,让我感到困惑的是最后一列的聚合。当前代码给了我一个0(在使用它时,我遇到了一些不同的错误。)

我知道每一行都是一个字符串,我需要将这些行拆分为一个值列表才能继续。任何建议/帮助都会非常有用

the_File = open("DoT_Info.txt", "r")
num_accidents = 0
for char in the_File.readlines():
    new_splt = char.split(',')
    num_accidents += int(new_splt[-1])
print('Total Incidents: ', num_accidents)
the_File.close()

Tags: 文件the字符串代码txt列表new错误
1条回答
网友
1楼 · 发布于 2024-06-14 06:00:48

假设每一行的最后一个元素总是事故的数量,这样的事情应该会起作用

import csv

with open("DoT_Info.txt", "r") as f:
    reader = csv.reader(f)
    # next(reader) - do this if there is a header row
    num_accidents = sum(int(row[-1]) for row in reader)
    print('Total Incidents: ', num_accidents)

相关问题 更多 >