Python FileNotFound

时间:2014-03-12 23:47:13

标签: python-3.x exception-handling file-not-found

我对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))

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

1 个答案:

答案 0 :(得分:17)

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