2 回答
TA贡献1820条经验 获得超9个赞
我不是 100% 确定您要做什么,但这是基于我对您的问题的理解的答案:
# Create a list named numbers
numbers = []
# Open the input file in read only
with open ('Numbers.txt', 'r') as input:
# read each line of the input file
for line in input:
# append each line to the list numbers
# rstrip removes the \n from the strings
numbers.append(line.rstrip())
print (type(numbers))
# outputs
<class 'list'>
print (numbers)
# outputs
['0', '50', '100']
# converts your list elements to int for summing
results = list(map(int, numbers))
print (sum(results))
# outputs
150
如果这不正确,请告诉我,我会调整我的答案。
TA贡献1775条经验 获得超11个赞
打开文件的一个好方法是使用上下文:
with open('path/to/file/Numbers.txt','r') as input_file:
for line in input_file.readlines():
do_stuff # knowing that they are string so you should convert to int
添加回答
举报