20

I am fairly new to python.

I am trying to make a script that will read sudoku solutions and determent if they are correct or not.

Things I need:

1] Prompt the user to enter a file/file path which includes the sudoku numbers. Its a .txt file of 9 rows and columns. Consist only of numbers.

2] Have some kind of an error handling.

3] Then, if the sudoku is valid, i should create a new text file using the same format as the original input file with the prefix "Correct_"

I have not fully finished the program, but I get this error when I put a false path or file name.

 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'

Here is my script:

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

Thanks, any advice or help will be appreciated.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
zilox
  • 209
  • 1
  • 2
  • 4
  • Do you have `example.txt` in the current working directory? – jfs Mar 12 '14 at 23:50
  • i have no idea in python. but in php i HAVE to say how to get files. like: `fopen('example.txt','rw');` which means open for read and write. – JohnnyJS Mar 12 '14 at 23:51
  • that file does not exist, its just to test the error handling to see if it works. Which is does not. Also, I have the read only at the open command. – zilox Mar 13 '14 at 00:06
  • Does this answer your question? [open() gives FileNotFoundError / IOError: '\[Errno 2\] No such file or directory'](https://stackoverflow.com/questions/12201928/open-gives-filenotfounderror-ioerror-errno-2-no-such-file-or-directory) – Karl Knechtel Jul 19 '23 at 02:59
  • This question is misleading to future readers, and should be deleted. The suggested duplicate link is a better explanation of the issue that people will be interested in when they find this question, because the question is very good at capturing search queries about unexpectedly not-found files. However, the question that was *actually asked* was about error handling, and was simply caused by a typo or a simple logical error. Answering it does not explain anything useful about error handling. It should have been closed as a typo when it was asked 9 years ago. – Karl Knechtel Jul 19 '23 at 03:01
  • Rather than a typo, the premise of the question doesn't make any sense: how could anyone reasonably expect the code that *asks for a name* for the file, to raise an exception about the file not being found? Therefore, how could exception handling around that spot possibly trap the error? – Karl Knechtel Jul 19 '23 at 03:02
  • Does this answer your question? [Pythonic way of write if open is successful](https://stackoverflow.com/questions/35975921/pythonic-way-of-write-if-open-is-successful) – Abdul Aziz Barkat Jul 19 '23 at 04:54

2 Answers2

49

try block should be around open. Not around 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
balki
  • 26,394
  • 30
  • 105
  • 151
-1

You can try adding this code before open() function:

import os
pathname = __file__
os.chdir(os.path.dirname(pathname))
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 14 '23 at 04:44