Anirudh Singh
Anirudh Singh

Reputation: 34

Can I import a python file and change a variable and save it parmanently?

I created a file 'user.py' and I gave it a variable 'coin' = '100'

coin = 100

I created another file and import this code

import user
print(user.coin) # Output 100
user.coin = 50

This variable is not updated in the 'user.py' file. I can to change the value from 99 to 50.

I want the change in 'user.py' file

coin = 50

Upvotes: 0

Views: 164

Answers (3)

Mateus Moutinho
Mateus Moutinho

Reputation: 152

assuming you know what you are doing, and there is no way to persist this data in json/yaml/xml do this:

import user 
from inspect import getsource
import re 
patterns = {
    'coin':200
}

text =getsource(user)
for key,value in patterns.items():
    finded = re.search(f'{key}.*',text).group()
    text = text.replace(finded,f'{key} = {value}')
with open('user.py','w') as arq:
    arq.write(text)

Upvotes: 0

curlyfriedd
curlyfriedd

Reputation: 3

The variable 'coin' is assigned statically in user.py. You cannot change this in runtime. To change the assignation you would need to import the user.py as a textfile and edit accordingly.

See here.

Upvotes: 0

Christian
Christian

Reputation: 1571

That's not how programming works. You for sure don't want to change the actual source code during execution.

What you are planing is more of a persistance topic. You could create a user that has a coins attribute and then store this somewhere - a file or a database for example. Then on the next execution you proceed from that state but your code should be unmodifiable except by yourself opening the file, writing stuff into it and saving again.

Upvotes: 1

Related Questions