【发布时间】:2026-02-23 01:00:01
【问题描述】:
我对 python 还很陌生。
我正在尝试制作一个脚本来读取数独解决方案并阻止它们是否正确。
我需要的东西:
1] 提示用户输入包含数独数字的文件/文件路径。它是一个包含 9 行和列的 .txt 文件。仅由数字组成。
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))
谢谢,我们将不胜感激任何建议或帮助。
【问题讨论】:
-
你的当前工作目录中有
example.txt吗? -
我对python一无所知。但在 php 中我不得不说如何获取文件。比如:
fopen('example.txt','rw');,表示开放读写。 -
该文件不存在,它只是为了测试错误处理以查看它是否有效。哪个不是。另外,我在 open 命令中只有只读权限。
标签: python-3.x exception-handling file-not-found