如何从另一个文件更改python文件中的字典值

2024-09-27 04:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改另一个文件中Dict中的值。File1.py包含编辑Dict的代码,File2.py包含Dict本身

File1.py正在生成代码,仅替换BTOK

File1.py:

with open('file2.py', 'r') as file :
    filedata = file.read()
    print (filedata.str(BTK['btk1']))
    for line in filedata:
        line['btk1'] = BTok
with open('file2.py', 'w') as file:
    file.write(line)

File2.py:

c = {
    'id' : 'C80e3ce43c3ea3e8d1511ec',
    'secret' : 'c10c371b4641010a750073925b0857'
}
rk = {
    't1' : 'ZTkwMGE1MGEt',
}
BTK = {
    'BTok' : '11eyJhbGc'
}

Tags: 代码pyaswithlineopenfile1dict
1条回答
网友
1楼 · 发布于 2024-09-27 04:29:48

如果您希望可靠地执行此操作,也就是说,无论字符串是否用'""""引用,对于它们具有的任何值以及您希望在值周围放置的任何新行,它都是有效的,那么您可能希望使用^{}来解析源代码并修改它。唯一不方便的是,模块本身无法生成代码,因此您需要安装一些额外的依赖项,例如^{},这基本上是一项相当简单的任务。在任何情况下,您都可以通过以下方式实现:

import ast
import astor

# To read from file:
# with open('file2.py', 'r') as f: code = f.read()
code = """
c = {
    'id' : 'C80e3ce43c3ea3e8d1511ec',
    'secret' : 'c10c371b4641010a750073925b0857'
}
rk = {
    't1' : 'ZTkwMGE1MGEt',
}
BTK = {
    'BTok' : '11eyJhbGc'
}
"""

# Value to replace
KEY = 'BTok'
NEW_VALUE = 'new_btok'
# Parse code
m = ast.parse(code)
# Go through module statements
for stmt in m.body:
    # Only look at assignments
    if not isinstance(stmt, ast.Assign): continue
    # Take right-hand side of the assignment
    value = stmt.value
    # Only look at dict values
    if not isinstance(value, ast.Dict): continue
    # Look for keys that match what we are looking for
    replace_idx = [i for i, k in enumerate(value.keys)
                   if isinstance(k, ast.Str) and k.s == KEY]
    # Replace corresponding values
    for i in replace_idx:
        value.values[i] = ast.Str(NEW_VALUE)

new_code = astor.to_source(m)
# To write to file:
# with open(`file2.py', 'w') as f: f.write(new_code)
print(new_code)
# c = {'id': 'C80e3ce43c3ea3e8d1511ec', 'secret':
#     'c10c371b4641010a750073925b0857'}
# rk = {'t1': 'ZTkwMGE1MGEt'}
# BTK = {'BTok': 'new_btok'}

相关问题 更多 >

    热门问题