0

My .ini data is essential to my python application. the configparser array/data is not available globally

import configparser

def write_config():
    config = configparser.ConfigParser()
    with open('config.ini', 'w') as configfile:
        config.write(configfile)


def read_config():
    config = configparser.ConfigParser()
    config.sections()
    config.read('config.ini')
    # things are fine here
    print(config['DEFAULT']['G'])



read_config()
#here, or from other functions, I cannot access or modify config like
print(config['DEFAULT']['G'])  
#I would also like to change config anywhere in app
config['DEFAULT']['G']="100"
#then just call write_config 
write_config()


What is the proper way to make my way (with functions) work? I do realize that skipping those functions and making the program flat would workaround the problem. I do know how to make a variable global, but I am apparently unable to make a variable in a function/external library global

user105939
  • 135
  • 5
  • 1
    Does this answer your question? [Using global variables between files?](https://stackoverflow.com/questions/13034496/using-global-variables-between-files) – Mike Scotty Nov 09 '20 at 21:09
  • @MikeScottly thank you, but I failed to implement that properly, I have updated my question with a clean example, could you please instruct me? – user105939 Nov 10 '20 at 08:07

1 Answers1

0

This works: I am not sure whatever this is a 100% correct method.

import configparser

config=[]
def write_config():
    global config 
    print("before")
    print(config['DEFAULT']['G'])

    #config = configparser.ConfigParser()
    print("after")
    print(config['DEFAULT']['G'])
    #config['DEFAULT']['R']="34"
    #config['DEFAULT']['G']="52"
    
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    

def read_config():
    global config 
    config = configparser.ConfigParser()
    config.sections()
    config.read('config.ini')


#write_config()
read_config()
print("here, or other functions, I cannot access or modify config")
print(config['DEFAULT']['G'])  #does not work.
#I would also like to change config anywhere in app
config['DEFAULT']['G']="100"
#then just call write_config 
write_config()

user105939
  • 135
  • 5