Python 我怎么停下来?
现在,它读取一个txt文件,并给出每行的总和。问题是,它会在我的txt文件中每行数字打印一行(假设我的txt文件有25个不同的数字,它会打印“累计总数是:”25次,将最后一个值加到下一个。我只想打印总数(一行)。这是用于家庭作业Python 我怎么停下来?,python,Python,现在,它读取一个txt文件,并给出每行的总和。问题是,它会在我的txt文件中每行数字打印一行(假设我的txt文件有25个不同的数字,它会打印“累计总数是:”25次,将最后一个值加到下一个。我只想打印总数(一行)。这是用于家庭作业 def main (): print() print("This will add together the numbers on number.txt") print() total, error = getsum() if
def main ():
print()
print("This will add together the numbers on number.txt")
print()
total, error = getsum()
if not error:
total = getsum()
print ("The sum is", total)
def getsum ():
error = False
total = 0
try:
infile = open("Numbers.txt", "r")
line = infile.readline()
while line != "":
readnum = float(line)
total = readnum + total
line = infile.readline()
print("The accumulated total is", total)
file.close()
except IOError:
print ("ERROR")
error = True
except ValueError:
print ("ERROR")
error = True
if error:
sum5 = 0
else:
sum5 = total
return total, error, thesum
main ()
要短得多…或者如果您担心无法关闭文件
with open("some.txt") as f:
print sum(map(float,filter(lambda line:line.strip(),f)))
请查看您的缩进谈论try函数?已修复。请编辑您的问题,使标题更具描述性。此外,您的措辞不清楚,这使得帮助您变得更困难。希望我能更好地解释我的问题。
filter
在迭代文件时是多余的-文件迭代器不会返回空字符串.sum(f行的float(line)
可能是最常用的,它避免了将所有行读入内存。你确定吗?我发誓我从一个文件迭代器中得到了空行字符串…+1如果你是对的,100%确定-试试看。啊,我看到它仍然返回“\n”…修复答案(至少在py2.6中…如果传递到float,将引发错误)请注意,原始代码根本没有过滤掉空行。它使用readline
来读取单独的行,因此测试空行是如何检查EOF条件的。因为您的代码使用迭代器版本的行读取,所以根本不需要进行检查。
with open("some.txt") as f:
print sum(map(float,filter(lambda line:line.strip(),f)))