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

Time:12-30

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

CodePudding user response:

Use the .write() method:

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