You need to enable JavaScript to run this app. 如何将数组写入文件、读取后追加内容再循环写回原文件?
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组写入文件、读取后追加内容再循环写回原文件?

问题原因

  • 读取文件逻辑错误:你将文件内的所有内容整体作为单个元素存入current_position数组,再次写入时会给这一整个字符串再套一层引号,导致出现嵌套的双引号问题。
  • 自行拼接数组存储格式容易出错:手动拼接带引号和逗号的字符串,不仅要处理多余的末尾分隔符,还要考虑转义问题,后续读取也很难直接还原成数组。

解决方案

推荐使用Python内置的json模块处理数组的序列化与反序列化,不需要手动拼接字符串,直接就能实现数组和文件内容的互相转换,代码更简洁也不会出现格式错误。

修正后的代码示例:

import json
import os

file_path = "board.txt"
current_position = []
# 读取文件还原数组
if os.path.exists(file_path) and os.path.getsize(file_path) > 4:
    with open(file_path, 'r', encoding='utf-8') as f:
        current_position = json.load(f)
    stockfish.set_position(current_position)
else:
    stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")

# 此处省略向current_position追加内容的代码
# 追加示例:current_position.append("e2e4")

# 直接将整个数组序列化写入文件
with open(file_path, 'w', encoding='utf-8') as f:
    json.dump(current_position, f)

# 测试读取验证
with open(file_path, 'r', encoding='utf-8') as f:
    print(json.load(f))

如果不想依赖JSON模块,要沿用原来的拼接格式,读取时需要先处理内容再拆分:

if os.path.exists(file_path) and os.path.getsize(file_path) > 4:
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read().strip().rstrip(',')
        # 去除引号、按分隔符拆分得到数组
        current_position = [item.strip('" ') for item in content.split(',') if item.strip()]
    stockfish.set_position(current_position)

内容的提问来源于stack exchange,提问作者Carter McKay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:45:03