Python 3.x Python:Try/Except

Python 3.x Python:Try/Except,python-3.x,Python 3.x,我希望这个也保持循环,直到输入正确的文件名。例如,如果我有一个名为test.txt的文件,那么我希望问题循环,直到找到正确的名称。有什么办法可以这样做吗 def validate(): file = "" flag = True while flag: try: file = input("Enter the name of the file: ") # If I leave false then it wi

我希望这个也保持循环,直到输入正确的文件名。例如,如果我有一个名为test.txt的文件,那么我希望问题循环,直到找到正确的名称。有什么办法可以这样做吗

def validate():
    file = ""
    flag = True
    while flag:
        try:
            file = input("Enter the name of the file: ")
            # If I leave false then it will quit the loop even if the file name 
            # does not exist. I only want it to exit once the correct file name 
            # is entered. Note the txt file will be created by the user so it
            # can always change.
            flag = False
        except FileNotFoundError:
            flag = True
    return file

这样行吗?实际打开文件以触发异常

def validate():
    file = ""
    flag = True
    while flag:
        try:
            file = input("Enter the name of the file: ")
            with open(file) as fh:
                # do something with fh if you want
            flag = False
        except FileNotFoundError:
            flag = True
    return file

有关在python中读取和写入文件的详细信息正确的方法是使用


你能解释一下那多余的一行是干什么的吗?@Nearrookoder多余的一行会打开文件。如果成功,它会将文件句柄放入
fh
,您可以使用它从文件中读取数据,将数据写入文件,等等。我编辑了我的帖子,并链接到文档以获取更多信息。因此fh只是一个包含打开文件的变量名?@nearocoder确实,它是一个文件对象,有自己的方法与打开的文件交互。例如,
fh.readLines()
将输出打开文件中的所有行。
import os

def validate():
    while True: #loop until the inputed filename is an existing file
        filename = input("Enter the name of the file: ")
        if os.path.isfile(filename): #filename refers to a file that exists and is not a folder
             return filename