如何将数组写入文件,然后调用该文件并向数组添加更多内容?

因此,正如标题所暗示的那样,我正在尝试将数组写入文件,但随后我需要调用该数组并向其追加更多内容,然后将其写回同一个文件,然后一遍又一遍地执行相同的过程。

我到目前为止的代码是:

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",

如果有人需要更多信息,我所有的代码都在这个replit上

回答

有几种方法可以做到这一点:

首先,使用换行符作为分隔符(简单,不是最节省空间的):

# 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()

如果您的字符串都具有相同的长度,则不需要分隔符:

# 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)]

最后,考虑pickle,它允许向/从二进制文件写入/读取 Python 对象:

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)


以上是如何将数组写入文件,然后调用该文件并向数组添加更多内容?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>