1

I'm finishing a program that I wrote in Python to make sure it's cross-platform. One last hurdle is about saving persistent data such as session history. In Windows, the files would be saved under the user profile's AppData\Local folder, on MacOS, well... I have no idea, and on Linux... it depends.

What are the best practices in such a case? Is there a library that will return the recommended, best-practice location for the platform that runs the application?

mrgou
  • 1,576
  • 2
  • 21
  • 45
  • I would recommend using a directory relative to the user's home. This may help:- https://stackoverflow.com/questions/4028904/what-is-the-correct-cross-platform-way-to-get-the-home-directory-in-python –  Aug 12 '21 at 09:03
  • Obviously, but is there a simple way to obtain the best-practice location for each platform (e.g. `AppData\Local` on Windows)? – mrgou Aug 12 '21 at 12:43
  • Unix style operating systems don't really have an equivalent of AppData\Local. That's why I suggested using something portable such as a directory relative to the user's home –  Aug 12 '21 at 13:08

1 Answers1

1

Based on @DarkKnight 's implicit confirmation that there is no Python module that returns the preferred location based on each platform (and assuming MacOS follows Linux system standards), I use this code:

import sys
import os

def app_folder(prog: str) -> str:
    def createFolder(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            raise

    if sys.platform == "win32":
        folder = os.path.join(os.path.expanduser("~"), "AppData", "Local", prog)
        createFolder(folder)
        return folder
    else:
        folder = os.path.join(os.path.expanduser("~"), "." + prog)
        createFolder(folder)
        return folder

(Note: I probably wouldn't take any risk in hardcoding \ or / as folder separator instead of using os.path.join() since it's already specific to each platform, but I just like to use code I can reuse, even line by line.)

mrgou
  • 1,576
  • 2
  • 21
  • 45