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
添加回答
舉報