【发布时间】:2016-12-07 00:09:28
【问题描述】:
我有 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,
}
file2.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 的 data 来自于套接字连接
dict2 = json.loads(data)
- 我想用来自套接字连接的数据更新 *file1**。
【问题讨论】:
-
为什么不将数据写入两个文件都可以读取的 JSON?据我所知,让一个 python 文件编辑另一个文件并没有任何好处,这似乎真的没有必要
标签: python file dictionary fileupdate