Reputation: 2448
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?
Upvotes: 1
Views: 483
Reputation: 11
change the sub directory variable with your folder name it will check for all 3 os and create folder their if not exist already and print the folder path.
import platform
from pathlib import Path
# check the os of pc
MACOS, LINUX, WINDOWS = (platform.system() == x for x in ['Darwin', 'Linux', 'Windows'])
#name whatever you want to use for your application
sub_dir = "example_app"
# Return the appropriate config directory for each operating system
if WINDOWS:
path = Path.home() / 'AppData' / 'Local' / sub_dir
elif MACOS: # macOS
path = Path.home() / 'Library' / 'Application Support' / sub_dir
elif LINUX:
path = Path.home() / '.config' / sub_dir
else:
raise ValueError(f'Unsupported operating system: {platform.system()}')
# Create the subdirectory if it does not exist
path.mkdir(parents=True, exist_ok=True)
print(path)
Upvotes: 1
Reputation: 2448
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.)
Upvotes: 2