如何与 try 一起循环,除了提示用户,直到给出有效的文件名?



所以所需的文件名是data.txt。我需要使用一个循环,该循环继续提示用户输入文件名,直到输入有效的文件名(data.txt(。我的尝试 - 除了必须在循环内。

我必须使用循环和 try-except 测试我的程序,以处理文件名的错误名称并继续提示用户,直到输入有效文件。

例如,如果我输入"数据",程序应该输出:

Enter name of file:
File data not found.
Enter new file name:
File to be processed is: data.txt
Average weight = 164.88
Average height = 69.38

这是我到目前为止的代码:

if __name__ == '__main__':
# Complete main section of code
# Prompt the user for the name of a file
user_input = input('Enter name of file:n')
# You should complete the following loop; it will contain the try-except code
found = False
while not found:
# Put your try-except code here
try:
my_file = open(user_input)
lines = my_file.read()

except: 
print('File {} not found'.format(user_input))
file_name = input('Enter new file name:')
# Print the name of the valid file
print("File to be processed is: ",file_name)
# Complete the remaining main section of code to loop through the file, compute the average weight and height, etc.
average_height = 0
average_weight = 0

with open('data.txt') as f:
for line in f:

sl = line.split(',')

average_height += int(str(sl[0]))
average_weight += int(str(sl[1]))

print("Average weight = {:.2f}".format(average_height / 8))
print("Average height = {:.2f}".format(average_weight / 8))

我们被要求利用

found = False
while not found: 

以及将我们的 try-except 代码放在那里。

到目前为止,我的代码只输出:

Enter name of file:
File data not found.
Enter new file name:

下面的计算打印("要处理的文件是:",file_name(应该是正确的。

所以我必须问,我如何使用带有try-except 的循环来提示用户,直到输入有效的文件(data.txt(?

您需要将except块更改为如下所示:

# Put your try-except code here
try:
my_file = open(user_input)
lines = my_file.read()
found = True
except: 
print('File {} not found'.format(user_input))
user_input = input('Enter new file name:')
continue

即便如此,如果用户将输入不是"data.txt"的现有文件名,您将继续像什么都没发生一样,这可能会导致以下异常(或其他不需要的行为(。 一般来说,你不应该用 try-exexcept 做这样的事情。相反,您应该将名称与所需名称进行比较。

此外,不应该失败的东西不需要在 try 块内,所以最好把readlines线放在try块之外

最后,在函数中编写代码更简洁。

最新更新