Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make an error message print to a file?

I am creating a Sudoku solver that sends the solved puzzles to a file, but one of our tasks is for the solver to tell you if a puzzle is unsolvable. I can get the error message to print in python or I can get the unsolved puzzle to go to the file, but I’m not sure how to send the message to the file. Does anyone know how to do this? Any help is appreciated!

def print_board(puzzle, index):
    # take the index of the board to write it to different files
    with open(f'files{index}.txt', 'w') as file: 
        #each row should have this formatting
        for vertical in range(len(puzzle)):
            if vertical % 3 == 0 and vertical != 0:
                print("- - - - - - - - - - - - - ", file=file)

            #each column should have this formatting
            for horizontal in range(len(puzzle[0])):
                if horizontal % 3 == 0 and horizontal != 0:
                    print(" | ", end="", file=file)

                if horizontal == 8:
                    print(puzzle[vertical][horizontal], file=file)
                else:
                    print(str(puzzle[vertical][horizontal]) + " ", end="", file=file)

if __name__ == "__main__":
    board_list = []
    board = []
    # open the file with puzzles in it
    with open('project.txt', 'r') as file:
        for line in file:
            # print(line)
            if line == "\n":
                print("\\n detected")
                board_list.append(board)
                print(board_list)
                board = []
            else:
                #print("constructing board")
                board.append(list(map(int, line.strip())))
        board_list.append(board)

    for i in range(len(board_list)):
        # print the final solved puzzles
       if (solve(board_list[i])):
        print_board(board_list[i], i);
       else:
           print ('no soluntion exists')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use the .write() method:

with open(f'files{index}.txt', 'w') as file:
     file.write('No solution exists.')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading