How can I get the path to the %APPDATA% directory in Python?

PythonAppdata

Python Problem Overview


How can I get the path to the %APPDATA% directory in Python?

Python Solutions


Solution 1 - Python

import os
print os.getenv('APPDATA')

Solution 2 - Python

You may use os.path.expandvars(path):

> Return the argument with environment variables expanded. Substrings of the form $name or ${name} are replaced by the value of environment variable name. Malformed variable names and references to non-existing variables are left unchanged. > > On Windows, %name% expansions are supported in addition to $name and ${name}.

This comes handy when combining the expanded value with other path components.

Example:

from os import path

sendto_dir = path.expandvars(r'%APPDATA%\Microsoft\Windows\SendTo')
dumps_dir = path.expandvars(r'%LOCALAPPDATA%\CrashDumps')

Solution 3 - Python

Although the question clearly asks about the Windows-specific %APPDATA% directory, perhaps you have ended up here looking for a cross-platform solution for getting the application data directory for the current user, which varies by OS.

As of Python 3.10, somewhat surprisingly, there is no built-in function to find this directory. However, there are third-party packages, the most popular of which seems to be appdirs, which provides functions to retrieve paths such as:

  • user data dir (user_data_dir)

  • user config dir (user_config_dir)

  • user cache dir (user_cache_dir)

  • site data dir (site_data_dir)

  • site config dir (site_config_dir)

  • user log dir (user_log_dir)

Solution 4 - Python

You can try doing:

import os
path = os.getenv('APPDATA')
array = os.listdir(path)
print array

Solution 5 - Python

You can use module called appdata. It was developed to get access to different paths for your application, including app data folder. Install it:

pip install appdata

And after that you can use it this way:

from appdata import AppDataPaths
app_paths = AppDataPaths()
app_paths.app_data_path  # for your app data path
app_paths.logs_path  # for logs folder path for your application

It allows to to get not only app data folder and logs folder but has other features to manage paths like managing config files paths. And it's customizable.

Links:

  1. Read the Docs - documentation.
  2. GitHub - source code.
  3. PyPI - package manager (pip).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfoxView Question on Stackoverflow
Solution 1 - PythonJon ClementsView Answer on Stackoverflow
Solution 2 - PythonAdrian WView Answer on Stackoverflow
Solution 3 - PythonMartin CejpView Answer on Stackoverflow
Solution 4 - PythonAominéView Answer on Stackoverflow
Solution 5 - PythonvoilalexView Answer on Stackoverflow