File in package not being written to

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)

include/config.ini file:

[file-locations]
mse-folder =
mse-exe =
mse-com =
mse-set =

I couldn’t reproduce this. My terminal session, after setting up the files you describe (including verification):

$ ls hax
config.py  include  main.py
$ cat hax/main.py 
from . import config
$ cat hax/config.py 
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)
$ cat hax/include/config.ini 
[file-locations]
mse-folder = 
mse-exe = 
mse-com = 
mse-set = 

$ python
Python 3.8.10 (default, May 26 2023, 14:05:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hax import main
>>> 
$ cat hax/include/config.ini 
[file-locations]
mse-folder = some value
mse-exe = 
mse-com = 
mse-set = 

What’s different in your setup?

Sorry, the main.py file is actually an __init__.py file in a package (see updated post)

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).

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Turns out the config.ini file was updating, but it was the copy in the site-packages folder, not my current directory :man_facepalming:

And now you understand why Python doesn’t do the Path(__file__).parent.resolve() trick for you implicitly. :wink: