I’m having a problem writing to a config file through an import via the configparser library.
In the package’s init file, I import another file from the same folder named config.py. When I import that, it should be writing to a “config.ini” file in a folder named “include”. However, the config.ini file is never written to. I’m not getting any errors, the rootDirectory variable is being given the correct value, and the files are all being found. What’s happening? Can files not be written to by an imported Python file?
in python terminal:
$ import my-package
package’s init file:
from . import config
config.py file:
from pathlib import Path
from configparser import ConfigParser
rootDirectory = Path(__file__).parent.resolve()
config = ConfigParser()
config.read(rootDirectory / 'include' / 'config.ini')
config['file-locations']['mse-folder'] = "some value"
with open(rootDirectory / 'include' / 'config.ini', 'w') as f:
config.write(f)
You might want to (a) put some print() calls here to ensure this is
being run and (b) print out what rootDirectory / 'include' / 'config.ini'
actually is, in case it isn’t as you expect.
I don’t see anything glaringly obviously wrong with your code (though as
a general rule of thumb, imports usually should not have side effects
like writing files).