简体   繁体   中英

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

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.

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM