的任务是让用户输入4个数字,然后将它们存储在一个文本文件,打开文本文件,展示了在不同线路的4个数字,然后得到这些数字的平均值并将其显示给用户。 这里是我到目前为止的代码:Python列表索引加载列表中未发现从文本文件
__author__ = 'Luca Sorrentino'
numbers = open("Numbers", 'r+')
numbers.truncate() #OPENS THE FILE AND DELETES THE PREVIOUS CONTENT
# Otherwise it prints out all the inputs into the file ever
numbers = open("Numbers", 'a') #Opens the file so that it can be added to
liist = list() #Creates a list called liist
def entry(): #Defines a function called entry, to enable the user to enter numbers
try:
inputt = float(input("Please enter a number")) #Stores the users input as a float in a variable
liist.append(inputt) #Appends the input into liist
except ValueError: #Error catching that loops until input is correct
print("Please try again. Ensure your input is a valid number in numerical form")
entry() #Runs entry function again to enable the user to retry.
x = 0
while x < 4: # While loop so that the program collects 4 numbers
entry()
x = x + 1
for inputt in liist:
numbers.write("%s\n" % inputt) #Writes liist into the text file
numbers.close() #Closes the file
numbers = open("Numbers", 'r+')
output = (numbers.readlines())
my_list = list()
my_list.append(output)
print(my_list)
print(my_list[1])
问题是装载数从文本文件回来,然后存储每一个作为变量,这样我可以让他们的平均值。 我似乎无法找到一种方法来明确定位每个数字,只是每个字节不是我想要的。
取出括号你的'readlines'功能,只是尝试'打印(输出)':你应该看到一个你的号码列表。 –
除了'print(my_list)'的错误输出和'print(my_list [1])的崩溃',这个代码还有其他一些问题。一旦你得到它的工作,我鼓励你问一个关于[codereview.se]的问题。 –
题外话:你的档案管理真的很差。你用“r +”打开文件只是截断(不是实际读取),然后(不关闭)重新打开追加,然后重新打开“r +”(这次读取,但不写入,所以+是毫无意义的)。只需打开一次“w +”,它可以让你读取和写入,并为你截断文件。当你完成写作(填充文件)时,你可以'回到开始读取它。您也可以切换到'with'语句来管理文件对象的生存期。 – ShadowRanger