How to avoid hidden files in file picker using tkinter filedialog.askopenfilename method?

Viewed 1615

I want to allow the users to select CSV files from the file manager. But it shows all hidden folders too, which is very inappropriate. How can I avoid hidden folders?

def importCSV(self):
            self.file =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))
2 Answers

After a bit of searching around I managed to find the answer here. I did some slight changes to the linked example so it will run on Python 3. To test it out, simply press ctrl+o after executing.

from tkinter import *
from tkinter import filedialog

root = Tk()

try:
    # call a dummy dialog with an impossible option to initialize the file
    # dialog without really getting a dialog window; this will throw a
    # TclError, so we need a try...except :
    try:
        root.tk.call('tk_getOpenFile', '-foobarbaz')
    except TclError:
        pass
    # now set the magic variables accordingly
    root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
    root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
except:
    pass

# a simple callback for testing:
def openfile(event):
    fname = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('CSV files', '*.csv'), ('all files', '*.*')))
    print(fname)
root.bind('<Control-o>', openfile)

root.mainloop()

The showHiddenVar is used to select if the hidden files will be displayed by default or not. If you don't want to allow the users to toggle between displaying and hiding the hidden files, then simply set showHiddenBtn to '0'.

filedialog.askopenfilename This line just opens a file picker of the Operating System. This is not Python's file picker.

You can disable the option to show hidden files in your operating system and they will disappear in the file picker too.

For windows, This option is available in File Explorer options in the Control Panel.

For Ubuntu, This option is available at filemanager > top menu->View->Show hidden files

Related