我希望这个也一直循环,直到输入正确的文件名。例如,如果我有一个名为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
答案 0 :(得分:1)
执行此操作的正确方法是使用path.isfile
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
答案 1 :(得分:0)
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
Here's有关在python中读取和写入文件的更多信息