成功找到用户输入的文件后,如何激活“ While”循环?

时间:2019-05-02 18:44:58

标签: python file while-loop

如果找到用户输入的文件,则需要激活while循环,“ while”循环中有一个“ try”,如果找到该文件,则打开文件

def main():
  customer_file = input("Enter the name of the file ")
  while _____:
    try:
      input_file = open(customer_file, "r")
    except FileNotFoundError:
      print("Invalid file Name")

  line = input_file.readline()
main()

1 个答案:

答案 0 :(得分:0)

例如:

def main():
    while True:
        customer_file = input("Enter the name of the file ")
        try:
            with open(customer_file, "r") as input_file:
                # better to use contex manager (with open...) to handle the file
                line = input_file.readline()
            break
        except FileNotFoundError:
            print("Invalid file Name")


main()