0

I have two files file 1 contains 3 variables

file1

var1 = 1
var2 = 2
var3 = 3

this file1 is constantly updated by an update file that opens file1 and changes the values. It works.

Now I have file2 and want to grab, also in a while loop, the values var1 to var3 from file1. first loop in file2 I get the values but the next loops , even when the values var1 to var 3 in file1 changes, they are not beeing updated.

update file

while True:
   var1 = api code
   var2 = api code
   var3 = api code 
   with open("path\file1.py", "a") as f:
        f.truncate(0)
        f.write(var1,var2,var2)

file 2

while True:
   from file1 import var1,var2,var3
   print(var1,var2,var3)

Can you please tell me why the values in file2 are not beeing updated from file1 and how can I change it. Thanks

  • [Why does Python import only once?](https://stackoverflow.com/q/65655755/4046632). That said, your setup is odd - you can always force reimport, but better way is just import `function` and call it to update result from the API. – buran Feb 04 '22 at 19:46
  • 1
    Or just write the values to a file in csv or json, and read the file in, rather that trying to use 'import' to read data. – JeffUK Feb 04 '22 at 20:22
  • Also please remember that the data file needs to be updated "atomically" or else there is a tiny but real chance that you read partially written file. Here is how to do it: https://stackoverflow.com/a/2333979/5378816 – VPfB Feb 04 '22 at 20:44
  • Thanks. Problem has been solved like Jeff suggested – Niklas Wägner Feb 13 '22 at 09:34
  • If you want like to avaid the problem if the partially written file. install "safer" – Niklas Wägner Feb 28 '22 at 13:10

0 Answers0