我需要创建一个名为open_file(message)
的函数,该函数提示用户重复输入文件名,直到打开正确的名称。如果未输入名称(空字符串(,则默认文件必须是名为 pass.txt
的文件。
我尝试使用try
和except
方法的while
循环。我对如何定义函数感到困惑。
def open_file(message):
'''Put your docstring here'''
filename = input("Enter the name of the file: ")
while True:
if filename == "" or filename == " ":
filename = "pass.txt"
fileopen = open("pass.txt", "r")
break
else:
try:
fileopen = open(filename, "r")
break
except FileNotFoundError:
print("file not found, try again.")
print(filename)
return fileopen
预期结果是打开用户输入的文件名,或者在找不到或打开输入的文件名时反复提示输入正确的文件名时打开默认文件。
在循环中移动输入语句
编辑:删除函数参数"消息",如果你不需要它
def open_file():
'''Put your docstring here'''
while True:
filename = input("Enter the name of the file: ")
if filename == "" or filename == " ":
filename = "pass.txt"
fileopen = open("pass.txt", "r")
break
else:
try:
fileopen = open(filename, "r")
break
except FileNotFoundError:
print("file not found, try again.")
print(filename)
return fileopen