How to add a line from the first python file to another file

For example: In the second file it is:

a=[] 

And the first is:

 from ty import a x = (15/5)*3+1 a.append(int(x)) 

How to make so that the value of x is stored in the list and was visible in the second file?

  • one
    Open the file, read all the text, find the right place, insert the desired text, save, close. - Enikeyschik
  • one
    The code you show does exactly what you want. No additional action is required. - andreymal
  • 3
    Why even such a tricky procedure? Very similar to the XY problem . - Enikeyschik
  • one
    @ Enikeyshchik function def print_a(): print(a) perfectly sees the contents of the list a in the second file. About the fact that the value needs to be saved to the file permanently in the file system, I repeat, the question does not say a word - andreymal pm
  • one
    @ V.Bychkov, as I understood in ty there is a variable with a list, for example a = [1, 2] You want to change the list in a file from another script so that in code ty after it becomes, for example a = [1, 2, 10] ? - gil9red pm

2 answers 2

There should be no problems if the list is simple, but problems can occur with nested lists.


Let ty.py :

 items = [] print(items) 

And the second file:

 from ty import items import re x = (15/5)*3+1 items.append(int(x)) print(items) # Считаем файл with open('ty.py', 'r', encoding='utf-8') as f: text = f.read() # Заменим список на другой и сохраним with open('ty.py', 'w', encoding='utf-8') as f: pattern = re.compile(r'(items = \[.*?\])') new_text = pattern.sub('items = {}'.format(items), text) f.write(new_text) 
  • Thank you very much - V. Bychkov

main.py

 from ty import a x = (15/5)*3+1 a.append(int(x)) 

ty.py

 a = [] from main import a print(a) #10 
  • one
    Monsieur knows a lot about perversions) - andreymal
  • but it works) - m0nte-cr1st0