[英]Sum up numbers in a file
myfile = open("file.txt")
lines = myfile.readlines
myfile.close
I am stuck here, having problems sum up numbers in file. 我被困在这里,在汇总文件数量时遇到问题。 They are
他们是
12
23
34
45
56
67
42
9001
您可以将每行转换为整数,然后使用sum
函数获得总和:
print(sum(map(int, open("file.txt"))))
This is a step by step process in order to achieve what you're asking for. 这是一步一步的过程,以实现您的要求。
file = open("numbers.txt", "r") #read the file
file = file.read().splitlines() #create a list where each value is a line of the file
file = list(map(int, file)) #convert each of the values on the list to "int"
print(sum(file)) #sum all the values inside the list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.