'Writeable directory on any Windows machine

I have a basic Windows question. I am a Linux user, but I am responsible for a program that needs to operate on the Windows file system.

I am seeking a list of safe, universally available high-level directories within which any Python program will be allowed to create directories and files on any Windows machine.

The following error message is being thrown when we try to run the code at bottom.

PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\arbitrary'

The code that throws the above error is:

import os
import platform

cwd = os.getcwd()
platform.system()

print("cwd is: ", cwd)

if platform.system() == 'Windows':
  print('W!')
  drive = cwd.split(':\\')[0] + ':\\'
  print('drive is: ', drive)

newpath = drive+'Program Files\\arbitrary' 
print('newpath is: ', newpath)

if not os.path.exists(newpath):
  os.makedirs(newpath)

Clearly, our program does not have permission to write to the Program Files directory.

But instead of requiring our users to have permissions on any given directory, we need to have the program specify writing to a directory which guaranteed will be writeable for any user that can run the program.



Solution 1:[1]

Windows provides several "special" locations where files are stored.

You would generally pick one of these if you need to write to files:

  • CSIDL_APPDATA Files that roam to different computers in NT domains. Good for configuration files. Also available as the %AppData% environment variable.
  • CSIDL_LOCAL_APPDATA Files that never roam. Good for cache and other things that is not vital or can be regenerated automatically. Also available as %LocalAppData%.
  • CSIDL_PERSONAL Documents. Don't store configuration files here.
  • %Public% Folder shared by all users on a machine.
  • %Temp% The temp directory. Only available as an environment variable.

See this question for methods to retrieve these in Python.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anders