使用 try-except 打开文件
Opening files using try-except
我需要创建一个名为 open_file(message)
的函数,提示用户重复输入文件名,直到打开正确的名称。如果未输入名称(空字符串),则默认文件需要是名为 pass.txt
.
的文件
我试过使用 while
循环和 try
和 except
方法。我对如何定义函数感到困惑。
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
预期结果是打开用户输入的文件名,如果找不到或无法打开输入的文件名,则打开默认文件,同时反复提示输入正确的文件名。
将你的输入语句移到 while 循环中
编辑: 如果不需要,请删除函数参数 "message"
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
我需要创建一个名为 open_file(message)
的函数,提示用户重复输入文件名,直到打开正确的名称。如果未输入名称(空字符串),则默认文件需要是名为 pass.txt
.
我试过使用 while
循环和 try
和 except
方法。我对如何定义函数感到困惑。
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
预期结果是打开用户输入的文件名,如果找不到或无法打开输入的文件名,则打开默认文件,同时反复提示输入正确的文件名。
将你的输入语句移到 while 循环中
编辑: 如果不需要,请删除函数参数 "message"
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