简体   繁体   English

你能更新从另一个 Python 文件导入的二维列表吗?

[英]Can you update a 2D list imported from another Python file?

I'm currently messing around with Python and grabbing variables from other Python files.我目前正在搞乱 Python 并从其他 Python 文件中获取变量。 So far I have:到目前为止,我有:

FILE_1.py FILE_1.py

data = [
    ["t1", "t2", "t3", "t4"],
    ["t5", "t6", "t7", "t8"]
]

FILE_2.py文件_2.py

from FILE_1 import data

# this only appends to the list imported into FILE_2, does not edit list in FILE_1.py
data.append(["t11","t22","t33","t44"])

Is there a way to append to list "data" in FILE_1? append 有没有办法在 FILE_1 中列出“数据”? I've seen some solutions about using numpy or just organizing data in a.cvs, but I wish to avoid those and use this way if it is possible.我已经看到了一些关于使用 numpy 或仅在 a.cvs 中组织数据的解决方案,但我希望避免使用这些解决方案,并在可能的情况下使用这种方式。

For clarification, there are no other methods in these files or processes to be run, nor are there any other variables/lists in FILE_1.为澄清起见,这些文件或进程中没有其他方法可以运行,FILE_1 中也没有任何其他变量/列表。 I just want to save any value gathered in FILE_2 to the list in FILE_1.我只想将 FILE_2 中收集的任何值保存到 FILE_1 中的列表中。

You cannot easily change data in other python files.您不能轻易更改其他 python 文件中的数据。

The easiest method would be to use JSON.最简单的方法是使用 JSON。

import json

jsonFile = open('file_1.json', 'w')
list = json.loads(jsonFile)

list.append(["t11","t22","t33","t44"])

json.dump(list, jsonFile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM