0

I'm currently messing around with Python and grabbing variables from other Python files. So far I have:

FILE_1.py

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

FILE_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? 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.

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. I just want to save any value gathered in FILE_2 to the list in FILE_1.

jts
  • 161
  • 1
  • 9
  • It will edit the list at runtime (and for the remaining duration of the program), as written, but it gets reset between runs, like anything else. Are you looking for a way for one file to literally modify the contents of another, permanently? Have you considered using, say, a JSON file to store this data instead (or some other format meant for _data storage_ rather than _executable code_)? – Green Cloak Guy Feb 18 '21 at 17:12
  • Maybe this will help you https://stackoverflow.com/questions/13034496/using-global-variables-between-files – A.Shenoy Feb 18 '21 at 17:14

1 Answers1

0

You cannot easily change data in other python files.

The easiest method would be to use JSON.

import json

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

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

json.dump(list, jsonFile)
Jan Ochwat
  • 82
  • 2
  • 8