Python文件未找到

c86crjj0  于 2023-02-14  发布在  Python
关注(0)|答案(2)|浏览(130)

我对python还是个新手。
我试图使一个脚本,将阅读数独解决方案和威慑,如果他们是正确的或不。

我需要的东西

1]提示用户输入一个包含数独数字的文件/文件路径。它是一个9行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))

谢谢,任何建议或帮助将不胜感激。

gojuced7

gojuced71#

try块应该在open附近。而不是在prompt附近。

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
pgx2nnw8

pgx2nnw82#

您可以尝试在open()函数之前添加以下代码:

import os
pathname = __file__
os.chdir(os.path.dirname(pathname))

相关问题