【问题标题】:How do I make an error message print to a file?如何将错误消息打印到文件?
【发布时间】:2021-12-30 00:06:51
【问题描述】:

我正在创建一个数独求解器,它将已解决的谜题发送到文件中,但我们的任务之一是让求解器告诉您谜题是否无法解决。我可以让错误消息在 python 中打印,或者我可以让未解决的难题转到文件,但我不确定如何将消息发送到文件。有谁知道如何做到这一点?任何帮助表示赞赏!

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

【问题讨论】:

  • 你知道如何打印到文件:print(message, file=file)那么有什么困难?
  • 只是因为当我在底部这样做时,它告诉我文件已关闭
  • 因为退出with(上下文管理器)块时,文件会自动关闭
  • 嗯,我明白了

标签: python file solver sudoku


【解决方案1】:

使用.write() 方法:

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

【讨论】:

  • 我会用它来代替我放在底部的 else 语句吗?
  • 是的,你会的。
  • printing 也有效,他们已经在使用它
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多