-1

So i have this setup in the same directory:

├── main.py
├── currencies.py

I'm using this code to import

from currencies import *

and i can nicely do my calculation on my main file but the currencies.py dictionary is not updated. Why is that? It seems i have a local dictionary if that makes sense.

Is it possible to update the dictionary in the other file too?

Takis Pan
  • 35
  • 6

1 Answers1

0

Python doesn't export to the other file, it makes a copy. If you import a variable, myvar, from another file, and then change the value of that variable, you are only changing the value of the variable in memory - it will not rewrite the other file to reflect the change. Python reads the variable on import, but doesn't write back to the file - export. What you're manipulating is a value stored to memory - a copy.

Once you've manipulated the data, you can then write it to file, but you wouldn't edit a separate python file. Instead, keep your data in a txt or csv or json file. Instead of using import, you could use:

with open('mydata.txt', 'r') as fp:   # 'r' for read
  mydata = fp.read()
  mydict = ast.literal_eval(mydata)

Above, I used ast.literal_eval() assuming I had a dictionary in a txt file represented as a string. If you use json, there would be a couple of differences. either way, you'll need to import json or ast.

Once you're done with your dict and want to save it again, use:

with open('mydata.txt', 'w') as fp:   # 'w' for write
  fp.write(str(mydict))               # convert back to a string

If you then need another python script to use the new data, they can both read and write from the same file.

Kyle Alm
  • 587
  • 3
  • 14
  • "Python doesn't export to the other file, it makes a copy". What does this mean? – Mad Physicist May 06 '20 at 14:46
  • 1
    If you import a variable, myvar, from another file, and then change the value of that variable, you are only changing the value of the variable in memory - it will not rewrite the other file to reflect the change. Python reads the variable on import, but doesn't write back to the file - export. What you're manipulating is a value stored to memory - a copy. – Kyle Alm May 06 '20 at 17:41
  • 1
    You may want to add that comment to your answer instead of the one cryptic phrase. The comment is quite lucid and helpful. – Mad Physicist May 06 '20 at 18:38