1

我有 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 连接到它。

有人可以帮我怎么做吗?

编辑:

  1. file1.py 可以保存为任何其他格式,例如 .json 或 .txt。这只是我的假设,将数据作为字典保存在单独的文件中可以轻松更新。
  2. file1.py 必须是一个单独的文件,它是一个配置文件,所以我不想将它合并到我的主文件中。
  3. 上面提到的dict2数据来自套接字连接

dict2 = json.loads(data)

  1. 我想用来自套接字连接的数据更新 *file1**。
4

4 回答 4

1

如果您尝试将字典打印回文件,您可以使用类似...

outFile = open("file1.py","w")
outFile.writeline("dict1 = " % (str(dict2)))
outFile.close()

最好有一个 json 文件,然后从文件中加载对象并将对象值写回文件。您可以让他们操作内存中的 json 对象,并简单地对其进行序列化。

Z

于 2016-08-01T19:52:42.673 回答
1

我认为您想将数据保存file1到一个单独.json的文件中,然后在第二个文件中读取该.json文件。这是您可以执行的操作:

文件1.py

import json
dict1 = {
        'a' : 1,      # value is integer
        'b' : '5xy',   # value is string
        'c' : '10xy',
        'd' : '1xy',
        'e' : 10,
        }
with open("filepath.json", "w+") as f:
    json.dump(dict1, f)

这会将字典转储dict1到一个json文件中,该文件存储在filepath.json.

然后,在您的第二个文件中:

文件2.py

import json

with open("pathname.json") as f:
    dict1 = json.load(f)

# dict1 = {
        'a' : 1,      # value is integer
        'b' : '5xy',   # value is string
        'c' : '10xy',
        'd' : '1xy',
        'e' : 10,
        }

dict1['a'] = dict2['some_int']     #int value
dict1['b'] = dict2['some_str']     #string value

注意:这不会更改您的第一个文件中的值。但是,如果您需要访问更改后的值,您可以dump将数据放入另一个文件,然后在需要数据时再次json加载该文件。json

于 2016-08-01T19:47:51.320 回答
0

最后,正如@Zaren 建议的那样,我在 python 文件中使用了 json 文件而不是字典。

这是我所做的:

  1. 将 file1.py修改为file1.json并以适当的格式存储数据。

  2. file2.py,我在需要时打开file1.json而不是在file1.jsonimport file1上使用json.dump&json.load

于 2016-08-02T00:29:51.430 回答
0

您应该使用 pickle 库来保存和加载字典https://wiki.python.org/moin/UsingPickle

下面是pickle的基本用法

   1 # Save a dictionary into a pickle file.
   2 import pickle
   3 
   4 favorite_color = { "lion": "yellow", "kitty": "red" }
   5 
   6 pickle.dump( favorite_color, open( "save.p", "wb" ) )



   1 # Load the dictionary back from the pickle file.
   2 import pickle
   3 
   4 favorite_color = pickle.load( open( "save.p", "rb" ) )
   5 # favorite_color is now { "lion": "yellow", "kitty": "red" }
于 2016-08-01T19:44:59.190 回答