Python tkinter filedialog asksaveasfilename returns "file not found" which is obvious because I want to create this file

166 Views Asked by At

Here is a very basic function, all I want that the filename is printed:

from tkinter import filedialog as file_dialog

def SaveFile():
    MyFile = file_dialog.asksaveasfilename()
    print(MyFile)

If I am running this function, the File Save dialog opens as it should. If I enter a filename for the file I want to save, i.e. Test.txt, and press the save button, I get a message the c:/Path/to/Test.xtx does not exist, which is obvious because I want to create it and expected to get a path as result.

If I select an existing file, I can confirm the overwriting warning dialog and then I get the path and filename.

I tried various parameters such as

MyFile = file_dialog.asksaveasfilename(defaultextension=".txt", title="Save File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))

But nothing helps. I really don't understand what is going wrong here because Saving a file usually means that it does not exist.

I am on Python 3.11.4

EDIT:

I discovered that I do have this behavior only if I want to save to "Documents" directory. If I choose any other directory it works.

1

There are 1 best solutions below

0
Inyoka On

This issue is present on Windows 10, and Windows 11 due to "Controlled Folder Access".

Press the Windows button and type "controlled folder access" to open the system settings page.

From there you have three options.

  1. Add an app to the list of allowed apps using the "Allow an app through controlled folder access" link. (Note : I tried adding a Python script, but it still couldn't save, once I packaged the script into an .exe file it worked.
  2. Save your file into a folder that is not protected such as your Desktop (see list of protected folders below).
  3. NOT RECOMMENDED : Turn off "Controlled folder access" and risk losing everything to ransomware.

Hopefully this should resolve your issue.

List of restricted folders : C:\Users<username>\Documents, C:\Users\Public\Documents, C:\Users<username>\Pictures, C:\Users\Public\Pictures, C:\Users\Public\Videos, C:\Users<username>\Videos, C:\Users<username>\Music, C:\Users\Public\Music, C:\Users<username>\Favorites