0

As mentioned in this related question, os.path.expanduser or pathlib.Path.home() can be used to get a path to the user home directory.

If a Python module needs to store some data, it will normally be stored somewhere in this directory, but the relative path to an appropriate location may vary by operating system. Programs running on Linux systems will typically store their settings and other data in a directory under ~/.local/share or in a dot-file directly under the home directory. In Windows, this data normally gets stored under $HOME\AppData if I recall correctly. Under macOS, the directory would be located under ~/Library/Application Support.

Is there a standard library module or third-party package available that will make it possible to do something like:

import homedir_storage
app_directory = homedir_storage.get_package_storage_dir('my_package_name')
sqlite3.connect(os.path.join(app_directory, "db.sqlite"))

Where homedir_storage represents the name of the hypothetical module/package?

BSMP
  • 4,596
  • 8
  • 33
  • 44
intuited
  • 23,174
  • 7
  • 66
  • 88
  • 1
    There's no guarantee the user's home directory will be persistent. Nothing to prevent a Linux user from putting it in /tmp for example. – Mark Ransom Aug 04 '21 at 01:47
  • @MarkRansom That's pretty unusual, though—presumably anyone doing so would expect many applications to not work normally – intuited Aug 04 '21 at 01:57

1 Answers1

0

To my surprise, I was unable to find a package on PyPI to fill this role, so I've created one.

It's called pypaxtor and it's really simple, just including a single function get_storage_location.

Example code from the README:

>>> import pypaxtor
>>> savedir = pypaxtor.get_storage_location('my_package')
>>> savedir  # if on Mac as user `rlyacht`
PosixPath('/Users/rlyacht/Library/Application Support/pypaxtor/my_package')
>>> with open(savedir / 'SaveFile.txt') as savefile:
...     # do stuff

If the above code is executed on a linux system, the saved file will be located at /home/rlyacht/.local/share/pypaxtor/my_package/SaveFile.txt.

If it's run under Windows, that location will be $HOME\AppData\Local\pypaxtor\my_package\SaveFile.txt.

That's pretty much it. Code is maintained at github. Licensed under the BSD license.

intuited
  • 23,174
  • 7
  • 66
  • 88