【发布时间】:2018-08-03 01:10:05
【问题描述】:
这是对我的previous post 的跟进。本质上,这个想法是将所有以 .math 结尾的文件的内容添加到 /home/pi/math 中。目录。目前我有 3 个文件:test.math、hello.math、hi.math - 它们都至少有 1.00。问题在于 1. 它似乎没有正确读取文件的内容,也没有将它们加起来。
这个想法是,它将添加这 3 个文件(最终我想将它们添加到一个变量中)并显示总数。请注意,我确实想包含浮点数。
import os
srcdir = "/home/pi/math/"
files = os.listdir(srcdir)
def sum_file_contents():
value = float()
for file in srcdir:
if file.endswith(('math')):
value += float(open(file, "r").read().strip())
return value
for file in files:
if file.endswith(('math')):
print(file)
print(sum_file_contents())
输出
test.math
0.0
hello.math
0.0
hi.math
0.0
【问题讨论】:
标签: python-3.x file sum