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

Python修改外部文件中列表的有效实现方案咨询

解决Python中修改另一个文件内列表的问题

问题原因

Python导入模块时,会将模块内容加载到内存中。你调用edit_list修改的是内存里的DATA对象,并不会直接修改磁盘上的details.py文件,所以关闭程序后文件内容不会变化,下次导入时仍会加载旧数据。

符合需求的解决方案

你要求不使用数据库、不重建details.py,同时让其他读取函数能获取最新数据,还要持久化修改到文件。这里提供两种可行方案,优先推荐第二种:


方案1:直接修改details.py文件(用AST安全更新代码)

通过AST解析Python代码,修改DATA的定义后写回文件,同时用文件锁避免并发冲突。

修改后的details.py代码:

DATA = [
    {'height': '184', 'width': '49'},
    {'height': '161', 'width': '31'},
    {'height': '197', 'width': '25'},
    {'height': '123', 'width': '56'},
    {'height': '152', 'width': '24'},
    {'height': '177', 'width': '27'},
]

def edit_list(h, w):
    # 先修改内存中的DATA
    for info in DATA:
        if info['height'] == h:
            info['width'] = w
            break  # 找到目标后停止遍历,提升效率
    
    # 同步修改到文件,用文件锁防止并发读写冲突
    from filelock import FileLock
    import os
    import ast

    file_path = os.path.abspath(__file__)
    lock_path = f"{file_path}.lock"
    
    with FileLock(lock_path):
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 用AST解析并替换DATA的定义
        tree = ast.parse(content)
        for node in ast.walk(tree):
            if isinstance(node, ast.Assign) and len(node.targets) == 1:
                target = node.targets[0]
                if isinstance(target, ast.Name) and target.id == 'DATA':
                    # 生成新DATA的AST节点
                    new_data_ast = ast.parse(repr(DATA)).body[0].value
                    node.value = new_data_ast
                    break
        
        # 将修改后的AST转回代码并写入文件
        updated_content = ast.unparse(tree)
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(updated_content)
    
    return True

注意事项:

  • 需要先安装filelock库:pip install filelock
  • 如果DATA包含自定义类等复杂对象,repr()可能无法正确序列化,这种情况不适合该方案。

方案2:用JSON文件存储数据(更安全简便)

把数据从details.py中分离到单独的JSON文件,details.py负责加载、修改和同步数据,避免直接操作Python代码文件。

步骤1:创建data.json文件(首次运行会自动生成):

[
  {"height": "184", "width": "49"},
  {"height": "161", "width": "31"},
  {"height": "197", "width": "25"},
  {"height": "123", "width": "56"},
  {"height": "152", "width": "24"},
  {"height": "177", "width": "27"}
]

步骤2:修改details.py代码:

import json
import os
from filelock import FileLock

# 定义数据文件路径
DATA_FILE = os.path.join(os.path.dirname(__file__), 'data.json')

# 初始化数据(如果文件不存在则创建)
if not os.path.exists(DATA_FILE):
    initial_data = [
        {'height': '184', 'width': '49'},
        {'height': '161', 'width': '31'},
        {'height': '197', 'width': '25'},
        {'height': '123', 'width': '56'},
        {'height': '152', 'width': '24'},
        {'height': '177', 'width': '27'},
    ]
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(initial_data, f, indent=2)

# 加载数据到内存
with open(DATA_FILE, 'r', encoding='utf-8') as f:
    DATA = json.load(f)

def edit_list(h, w):
    updated = False
    # 修改内存中的数据
    for info in DATA:
        if info['height'] == h:
            info['width'] = w
            updated = True
            break
    
    if updated:
        # 同步修改到JSON文件,加锁防止冲突
        lock_path = f"{DATA_FILE}.lock"
        with FileLock(lock_path):
            with open(DATA_FILE, 'w', encoding='utf-8') as f:
                json.dump(DATA, f, indent=2)
    
    return updated

方案优势:

  • 无需操作Python代码文件,避免语法错误风险
  • JSON格式通用,其他工具也能查看编辑数据
  • 内存中的DATA始终和文件同步,其他读取函数能直接获取最新值
  • 文件锁保证多进程/线程读写时的安全性

如何验证效果

运行models.py后:

  1. 查看data.json(方案2)或details.py(方案1),确认数据已更新
  2. 其他导入details.DATA的代码,能直接获取修改后的内存数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:11:09