Carter McKay
Carter McKay

Reputation: 490

How to write an array to a file and then call that file and add more to the array?

So as the title suggests I'm trying to write an array to a file, but then I need to recall that array and append more to it and then write it back to the same file, and then this same process over and over again.

The code I'm have so far is:

c = open(r"board.txt", "r")

current_position = []

if filesize > 4:
    current_position = [c.read()]
    print(current_position)
    stockfish.set_position(current_position)
    
else:
    stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")

#There is a lot more code here that appends stuff to the array but I don't want to #add anything that will be irrelevant to the problem

with open('board.txt', 'w') as filehandle:
    for listitem in current_position:
        filehandle.write('"%s", ' % listitem)

z = open(r"board.txt", "r")
print(z.read())    
My array end up looking like this when I read the file

""d2d4", "d7d5", ", "a2a4", "e2e4",

All my code is on this replit if anyone needs more info

Upvotes: 3

Views: 1803

Answers (2)

William Bradley
William Bradley

Reputation: 365

A few ways to do this:

First, use newline as a delimiter (simple, not the most space efficient):

# write
my_array = ['d2d4', 'd7d5']
with open('board.txt', 'w+') as f:
    f.writelines([i + '\n' for i in my_array])

# read
with open('board.txt') as f:
    my_array = f.read().splitlines()

If your character strings all have the same length, you don't need a delimiter:

# write
my_array = ['d2d4', 'd7d5'] # must all be length 4 strs
with open('board.txt', 'w+') as f:
    f.writelines(my_array)

# read file, splitting string into groups of 4 characters
with open('board.txt') as f:
    in_str = f.read()

my_array = [in_str[i:i+4] for i in range(0, len(in_str), 4)]

Finally, consider pickle, which allows writing/reading Python objects to/from binary files:

import pickle

# write
my_array = ['d2d4', 'd7d5']
with open('board.board', 'wb+') as f: # custom file extension, can be anything
    pickle.dump(my_array, f)

# read
with open('board.board', 'rb') as f:
    my_array = pickle.load(f)

Upvotes: 5

devReddit
devReddit

Reputation: 2947

as you're reusing the file to append data to it, you should replace:

open('board.txt', 'w')

with

open('board.txt', 'a')

a denotes append mode. Which will not overwrite what you have in your file, it will append to it.

Upvotes: 2

Related Questions