Python function to choose a file in my PC

I have a Python function that can search a folder in my PC, but I want to transform it in a function that can search for a file, specifically with the DOCX or PDF extensiom (i’ll mange that later). This is what I have until now:

def choose_file(self):

    root = Tk()
    root.withdraw()
    path = askdirectory(title='Choose file')
    os.chdir(path)

That opens a Tkinter window that allows me to search for a folder. As I said before, I want to transform it into a tkinter window that searches a DOCX or PDF file, any solution? Thanks in advance!

Answer

You should use askopenfilename. With askdirectory you will just get the directory name, so:

from tkinter import filedialog

def choose_file(self):
    root = Tk()
    root.withdraw()
    filetypes=[('DOCX','*.docx'),('PDF','*.pdf')] # Required file types
    path = filedialog.askopenfilename(title='Choose file',filetypes=filetypes)
    # os.chdir(path) There is no need of this now, as specific files will be only selected

If you want to choose multiple files then use askopenfilenames instead or add an additional option to askopenfilename, like:

path = filedialog.askopenfilename(title='Choose file',filetypes=filetypes,multiple=True)

Leave a Reply

Your email address will not be published. Required fields are marked *