Python中try...except无法捕获FileNotFoundError问题修复需求
修复路径验证逻辑的解决方案
原代码的第二个try-except块无效的核心原因是:input()仅读取用户输入的字符串,不会触发FileNotFoundError,异常捕获逻辑完全起不到作用。要实现路径有效性校验,需要主动检查输入路径是否存在,调整后的逻辑如下:
- 若用户输入非空路径,先验证路径是否真实存在
- 路径无效时提示用户重新输入,直到输入有效路径或留空(默认使用当前工作目录)
- 确保在创建文件前完成路径校验,避免向无效路径写入文件
修复后的完整代码:
# This program can make files of any type as you wish import os # 改用完整os模块,方便路径检查与当前目录获取 # Ask's For extension file_extension = input("Please enter the file type as .extension (E. g. ->> .txt , .py , .png , etc): ") # Takes number of files that are required and if something wrong is entered such as char then throws error while True: try: number_of_files = int(input('Please Enter the number of files needed: ')) break except ValueError: print("Enter a valid number...") # Takes the name of file file_name = input("Please enter the name of file: ") # Takes path of file - 修复后的路径验证逻辑 while True: path_name = input("Enter the path if specified else ignore\n(E.g. ->> D:/alpha/ would store in folder alpha inside Disc D)\nNote add a \"/\" in between and also at end: ") # 处理空输入:自动使用当前工作目录 if not path_name: path_name = os.getcwd() break # 验证路径是否存在 if os.path.exists(path_name): break else: print("Enter a valid path or just press enter to continue") # To make a appropriate name file_name_with_path = os.path.join(path_name, file_name) # Makes appropriate files for i in range(1, (number_of_files+1)): with open(f"{file_name_with_path}-{i}{file_extension}", "w") as f: f.write('')
关键修改说明:
- 替换单独导入
path为完整os模块,方便调用路径检查和当前目录获取函数 - 移除无效的
try-except块,改为主动校验路径存在性 - 增加空输入处理:自动使用当前工作目录(
os.getcwd()) - 每次输入路径后立即验证有效性,无效则提示重新输入
内容的提问来源于stack exchange,提问作者Rishabh Shah
相关产品推荐
相关产品推荐

