0

I have the following function in python:

 def writeWinningBoards():
    f = open("goodBoards.txt", "a")
    for row in tableros:
        for index, value in enumerate(row):
            if value == 1:
                row[index] = 'x'
            elif value == 2:
                row[index] = ' '
            elif value == 3:
                row[index] = 'o'
        row = np.array(row).reshape(3,3)
        f.write(row)
        print row
    f.close()

How can a I write to a file, the console representation of the array, when row is printed I have this:

 ['o' 'o' 'x']
 ['x' 'x' 'x']
 ['o' 'x' 'o']

but in the file I get something like this:

 x    o   x      o x        x o      xo    o  x   

How could I do this ? I just want a user-friendly way of storing tic tac toe gameboards for reading.

3 Answers 3

1

Many ways, the one I'd suggest is:

row_reshaped = np.array(row).reshape(3,3)
row_reshaped_as_base_array = row_reshaped.tolist()
row_reshaped_as_json = json.dumps(row_reshaped_as_base_array
with open("goodBoards.txt", "a") as f:
   f.write(row_reshaped_as_json)

I don't do method chaining and find list comprehensions a bit too terse for me.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is one option:

import numpy as np
import pandas as pd

a = np.array([["x", "o"], ["o", "x"]])

df = pd.DataFrame(a)
df.to_csv("my_file.txt", header=False, index=False, sep=" ")

Result:

$ cat my_file.txt
x o
o x

Comments

0

The difference between f.write(row) and print row isn't just that one writes to a file and the other writes to the screen. In python, the print statement will append a newline after each call, whereas the write method on an open file object will not.

1 Comment

This isn't' an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.