gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:24:06 27 4
gpt4 key购买 nike

因此,正如标题所示,我正在尝试将数组写入文件,但随后我需要调用该数组并将更多内容附加到它,然后将其写回同一个文件,然后再执行相同的过程重新来过。

到目前为止我的代码是:

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)

关于python - 如何将数组写入文件,然后调用该文件并将更多内容添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68706719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com