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

标签 python

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

到目前为止我的代码是:

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/

相关文章:

python - Rust Numpy 库 - 按行迭代:无法构建返回行而不是单个值的 NpySingleIterBuilder::readwrite

python - 构建 Docker 容器时 python3 中的神秘 UnicodeDecodeError

python - 测试 send_email 不起作用

Python 初学者 - 如何将回归线与点击等同并以图形方式显示?

javascript - Django 和tinymce

python - 在 python 中使用 google api 添加多个收件人?

python - 从 SharedCtypes 数组设置 Tkinter 标签文本

python - 如何为相关对象创建自定义管理器?

python - 如何停止 SparkContext

python - 类返回语句不打印任何输出