[英]How can i write my python code so that it sums the numbers from a .txt file?
yeah so i have been working on this for hours and i can't get it to work.是的,所以我已经为此工作了几个小时,但我无法让它工作。 Sob story aside here is my code
除了这里的悲伤故事是我的代码
numbers_file = open('numbers.txt', 'r')
#print(numbers_file.read())
for line in numbers_file():
sum(line)
I left the "#print(numbers_file.read())" in there just to show my thinking.我把“#print(numbers_file.read())”留在那里只是为了展示我的想法。
Any input on how i can do this would be very nice.关于我如何做到这一点的任何输入都会非常好。
Thanks谢谢
Try尝试
print(sum(map(float, open('numbers.txt').read().split())))
or或者
import pathlib
import math
print(math.fsum(map(float, pathlib.Path('numbers.txt').read_text().split())))
Both TextIOWrapper.read and Path.read_text return the contents of the file as a string.TextIOWrapper.read和Path.read_text都将文件的内容作为字符串返回。 str.split split the string according to any whitespace.
str.split根据任何空格分割字符串。 map applies a function float to every word.
map将函数float应用于每个单词。 sum computes the total.
sum计算总数。 The second version is more pedantic.
第二个版本更加迂腐。 It closes the file and uses an accurate floating point sum.
它关闭文件并使用准确的浮点和。
Here is a simple solution that will work as long as the file contains only numbers (integers or floats), separated by whitespace (including newlines).这是一个简单的解决方案,只要文件只包含数字(整数或浮点数),用空格分隔(包括换行符),它就可以工作。 (It's good practice to open files with a context manager, ie, the
with ... as
part, as it closes the file automatically.) (最好使用上下文管理器打开文件,即
with ... as
一部分,因为它会自动关闭文件。)
total = 0
with open('numbers.txt', mode='r') as numbers_file:
for number in numbers_file.read().split():
total += float(number)
print(total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.