如何将错误消息打印到文件中?
How do I make an error message print to a file?
我正在创建一个数独解算器,它将解出的谜题发送到一个文件中,但我们的任务之一是让解算器告诉您某个谜题是否无法解出。我可以在 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')
使用.write()
方法:
with open(f'files{index}.txt', 'w') as file:
file.write('No solution exists.')
我正在创建一个数独解算器,它将解出的谜题发送到一个文件中,但我们的任务之一是让解算器告诉您某个谜题是否无法解出。我可以在 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')
使用.write()
方法:
with open(f'files{index}.txt', 'w') as file:
file.write('No solution exists.')