Python 文件未找到
我刚开始学习Python。
我想写一个脚本,能够读取数独的解答,并判断它们是否正确。
我需要做的事情:
1] 提示用户输入一个文件或文件路径,这个文件里包含数独的数字。这个文件是一个.txt格式的文件,有9行9列,里面只包含数字。
2] 需要有一些错误处理的功能。
3] 如果数独是有效的,我应该创建一个新的文本文件,格式和原始输入文件一样,只是在文件名前加上“Correct_”这个前缀。
我还没有完全完成这个程序,但当我输入错误的路径或文件名时,会出现这个错误。
Hello to Sudoku valitator,
Please type in the path to your file and press 'Enter': example.txt #This is a non existing file, to test the Error Exception
'Traceback (most recent call last):
File "C:/Users/FEDROS/Desktop/bs.py", line 9, in <module>
sudoku = open(prompt, 'r').readlines()
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
这是我的脚本:
while True:
try:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
break
except (FileNotFoundError, IOError):
print("Wrong file or file path")
sudoku = open(prompt, 'r').readlines()
def check(game):
n = len(game)
if n < (1):
return False
for i in range(0, n):
horizontal = []
vertical = []
for k in range(0, n):
if game[k][i] in vertical:
return ("File checked for errors. Your options are wrong!")
vertical.append(game[k][i])
if game[i][k] in horizontal:
return ("File checked for errors. Your options are wrong!")
horizontal.append(game[i][k])
return ("File checked for errors. Your options are correct!")
print (check(sudoku))
谢谢,任何建议或帮助都非常感谢。
2 个回答
-1
你可以试着在open()函数之前加上这段代码:
import os
pathname = __file__
os.chdir(os.path.dirname(pathname))
51
应该把 try
代码块放在打开文件的地方,而不是放在提示用户输入的地方。
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break