【问题标题】:Try and Except inside of a While Loop - Opening files在 While 循环内尝试和排除 - 打开文件
【发布时间】:2024-01-14 23:10:01
【问题描述】:

我正在尝试提示用户读取文件,如果在目录中找不到该文件,它将打印一条消息,然后重新提示用户。对于错误处理,我尝试使用 Try 和 except 语句,并尝试使用 while 循环对其进行循环。请帮助,为什么这不起作用!

while True:

    try:
        input_file = input('Enter the name of the Input File: ' )
        ifile = (input_file, 'r' )
        continue

    except:
        print('File not found. Try again.')

【问题讨论】:

  • continue 因为循环中的最后一条语句是多余的。它没有效果。
  • 你不会在任何地方打开文件。
  • @C.Slates 在收到有效的文件名后,您需要打破外观使用break 而不是continue
  • @melpomene 我觉得自己真的很笨哈哈,但谢谢你帮了很多忙。
  • @shanmuga 这也帮助我摆脱了循环,没听懂。

标签: python loops while-loop try-catch except


【解决方案1】:

os.path.isfile检查会更有意义

import os

while True:

    input_file = input('Enter the name of the Input File: ')
    if not os.path.isfile(input_file):
        print('File not found. Try again.')
        continue
    break

print('File found!')

【讨论】:

    最近更新 更多