You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中永久追加数据到另一个文件的数组?

解决Python列表永久写入文件的问题

你之前的方法只修改了内存中的table对象副本,不会自动同步到database.py源文件。要实现永久保存,需要手动将修改后的列表写入文件,下面提供两种可行方案:

方案一:直接更新database.py中的table变量

这种方法会直接修改database.py文件,把更新后的列表重新写入:

# main.py
from database import table

# 追加新行
row = ["apples", "oranges", "pears"]
table.append(row)

# 将修改后的table写入database.py
with open("database.py", "w", encoding="utf-8") as f:
    # 用repr()把列表转换成Python可解析的字符串格式
    file_content = f"# database.py\n\ntable = {repr(table)}"
    f.write(file_content)

执行后database.py的内容会自动更新为你期望的样子。注意:如果database.py里还有其他代码,这种方法会覆盖整个文件,仅适合文件中只有table变量的场景。

方案二:用JSON格式存储数据(推荐)

直接修改Python代码文件存在格式风险,更专业的做法是用JSON专门存储数据:

  1. 新建database.json文件,初始内容:
[
    ["cars", "boats", "trains"],
    ["peanut butter", "jelly", "bread"]
]
  1. 修改main.py代码实现读写:
# main.py
import json

# 读取JSON文件中的数据
with open("database.json", "r", encoding="utf-8") as f:
    table = json.load(f)

# 追加新行
row = ["apples", "oranges", "pears"]
table.append(row)

# 将更新后的数据写回JSON文件
with open("database.json", "w", encoding="utf-8") as f:
    json.dump(table, f, indent=2)  # indent=2保证格式化输出,方便阅读

这种方法更安全,数据格式清晰,也支持其他语言读取,适合长期的数据持久化需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:05:21