我有 2 个 python 文件,file1.py 只有 1 个字典,我想从 file2.py 读取和写入该字典。两个文件都在同一个目录中。
我可以使用import file1从中读取,但我如何写入该文件。
片段:
file1.py(file1 中没有其他内容,除了以下数据)
dict1 = {
'a' : 1, # value is integer
'b' : '5xy', # value is string
'c' : '10xy',
'd' : '1xy',
'e' : 10,
}
文件2.py
import file1
import json
print file1.dict1['a'] #this works fine
print file1.dict1['b']
# Now I want to update the value of a & b, something like this:
dict2 = json.loads(data)
file1.dict1['a'] = dict2.['some_int'] #int value
file1.dict1['b'] = dict2.['some_str'] #string value
我使用字典而不是文本文件的主要原因是因为要更新的新值来自 json 数据并将其转换为字典更简单,因为每次我想更新dict1时都无需进行字符串解析。
问题是,当我从 dict2 更新值时,我希望将这些值写入 file1 中的 dict1
此外,代码在 Raspberry Pi 上运行,我使用 Ubuntu 机器通过 SSH 连接到它。
有人可以帮我怎么做吗?
编辑:
- file1.py 可以保存为任何其他格式,例如 .json 或 .txt。这只是我的假设,将数据作为字典保存在单独的文件中可以轻松更新。
- file1.py 必须是一个单独的文件,它是一个配置文件,所以我不想将它合并到我的主文件中。
- 上面提到的dict2的数据来自套接字连接
dict2 = json.loads(data)
- 我想用来自套接字连接的数据更新 *file1**。