我對python相當陌生。Python FileNotFound
我想製作一個腳本,它將讀取數獨解決方案並確定它們是否正確。
事情,我需要:
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'? – jfs
我不知道在python中。但在PHP中,我必須說如何獲取文件。例如:'fopen('example.txt','rw');'這意味着可以讀取和寫入。 – JonnieJS
該文件不存在,它只是爲了測試錯誤處理,看看它是否工作。哪個不是。另外,我只在打開命令時閱讀。 – zilox