PermissionError: [Errno 13] Permission denied when saving a txt file with pyinstaller

3.4k views Asked by At

I want to create a simple .exe file based on tkinter code. For now, I just want the .exe to save a .txt file when a button is clicked.

When running the tkinter code, it works without problem.

However, when I try to run the .exe file which is produced with pyinstaller, I get the error:

PermissionError: [Errno 13] Permission denied "C:\Users\path\to\file.txt"

I have tried to run the .exe file as an admin and the error still occurs.

Here is the simple tkinter_code:

import tkinter as tk

def test() : 
    directory = r'C:\Users\Path\to\file.txt'
    with open(directory, 'w') as f:
        print(directory)
        f.write('readme')
        
#Instantiate the window
my_w = tk.Tk()
my_w.geometry("800x600")  # Size of the window 
my_w.title('test')

b2 = tk.Button(my_w, text='Generate file', 
   width=20,command = lambda:test())   
b2.grid(row = 1, column = 1)


if __name__ == '__main__':
    my_w.mainloop()

I create the .exe with:

pyinstaller --onefile test.py

Any help would be appreciated & Thanks in advance.

2

There are 2 answers

1
n kir On BEST ANSWER

I managed to make it work by uninstalling and reinstalling anaconda (from Python 3.7 to Python 3.9)

0
EasyWay Coder On

You are getting the permission error because you are trying to save your file in C:\Users\path\to\file.txt. The open() command isn't allowed to edit the Users directory in a PC. So, if you try to open or save or edit any file in there, you will get this error as it is not an admin file. Only an admin can edit the file in that directory. You can try Run file as administrator option, but I do not know if it will work. Saving the file in any other drive might work. (Depends on which directory you are saving the file)