How to write to "Program Files (x86)" without Admin rights?

289 Views Asked by At

I'm using PyInstaller to make an exe and InstallForge to make an installer for it. Before InstallForge I could use with open("Saves/default.sav", "w"): ... to write to a file. Having installed the application to "Program Files (x86)" I need administrator access to save files. Is there a way that doesn't require admin rights?

File structure:

- Project Folder  
  |- main.py  
  |- Saves  
  |  |- default.sav  
  |  
  |- Assets  
     |- ...  

My code:

import pygame
from pygame.locals import *

pygame.init()
app = pygame.display.set_mode((640, 480), RESIZABLE)

def saveFile(contents):
    with open("Saves/default.sav", "w") as f:
        f.write(contents)

run = True
while run:
    for ev in pygame.event.get():
        if ev.type == QUIT:
            saveFile("some_placeholder_data")
            pygame.quit()
            run = False

    if not run:
        break

This way all data gets saved when the program closes. I tried with open("...", "w") as f: ... and open() and close() separately. Both result in :

PermissionError: [Errno 13] Permission denied

1

There are 1 best solutions below

0
ash-ferr On

This answer assumes Windows OS.

You are trying to write the file to the directory where the executable is installed... The "Program Files (x86)" directory shouldn't be used for your purpose. Try changing the file path to a user directory.

I would do the following:

#add this
#Path to file
path = 'C:/User_directory/Program_save_folder/default.sav'
#Save File function
def saveFile(contents,path=path):
    with open(path, "w") as f:
        f.write(contents)
#This provides you with a default path and the ability to take a different 
#path as an input to the function

However, using the os library you should:

#Path to file
path = 'C:/User_directory/Program_save_folder/default.sav'
#Save File function
def saveFile(contents,path=path):
    directory = os.path.dirname(path)
    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(path, "w") as f:
        f.write(contents)