Having some issues with a print to .txt
function. There are a lot of options available, and I've tried several methods, but I'm running into errors.
I've created a Sudoku solver that reads an amount of 9×9 arrays from a text file and solves all of them. I have a working function that prints them into the terminal, but I need to output the results, formatted as they are in the terminal, into a text file.
Is there someway to amend the print function below to achieve that? I have a semi-working separate function that outputs to a .txt
, but in an unformatted method and only one of the four puzzle arrays I've been using.
Thank you for your help.
def print_board(board):
for x in range(len(board)):
if x % 3 == 0 and x != 0:
print("- - - - - - - - - ")
for y in range(len(board[0])):
if y % 3 == 0 and y != 0:
print("| ", end="")
if y == 8:
print(board[x][y])
else:
print(str(board[x][y]) + " ", end="")
return
This is the export function that is only displaying one array.
def export_board(board):
outputfile=open('solvedpuzzles.txt', 'w')
print(output, file=outputfile)
outputfile.close()
This is the format I need to achieve, that is currently working in the terminal from print_board
4 8 3 | 9 2 1 | 6 5 7
9 6 7 | 3 4 5 | 8 2 1
2 5 1 | 8 7 6 | 4 9 3
- - - - - - - - -
5 4 8 | 1 3 2 | 9 7 6
7 2 9 | 5 6 4 | 1 3 8
1 3 6 | 7 9 8 | 2 4 5
- - - - - - - - -
3 7 2 | 6 8 9 | 5 1 4
8 1 4 | 2 5 3 | 7 6 9
6 9 5 | 4 1 7 | 3 8 2
Edit: I have made some adjustments, and have this:
def print_board(boards):
output = ''
with open("puzzleoutput.txt", "a") as file:
for x in range(len(board)):
if x % 3 == 0 and x != 0:
output += (str("\n - - - - - - - - - "))
for y in range(len(board[0])):
if y % 3 == 0 and y != 0:
output += (str(" | "))
if y == 8:
output += (str(board[x][y]))
else:
output += (str(f"{board[x][y]} "))
file.write(str(output))
return
Can someone please let me know how to add a new line for the individual rows of 9? It prints out the array as such, and I think I've nearly cracked it
4 8 3 | 9 2 1 | 6 5 79 6 7 | 3 4 5 | 8 2 12 5 1 | 8 7 6 | 4 9 3
- - - - - - - - - 5 4 8 | 1 3 2 | 9 7 67 2 9 | 5 6 4 | 1 3 8
- - - - - - - - - 3 7 2 | 6 8 9 | 5 1 48 1 4 | 2 5 3 | 7 6 9