Parsing the results of askopenfilenames()?

11,433

Solution 1

This is actually a bug on the Windows version that has been present since around the 2.6 release of Python. You can find the issue on their tracker, and there's a workaround in the comments (I have not personally tried this workaround because I'm on Linux, which returns a proper tuple). I'm not aware of a fix since then, and the issue has not been marked as closed/resolved.

The suggested workaround in the comment is essentially to do this:

master = Tk()
files = askopenfilenames(initialdir="C:\\Users\\BVCAP\\Videos", title="Select files")
files = master.tk.splitlist(files) #Possible workaround
self.num_files.set(len(files))

Solution 2

When implementing this method today, askopenfilenames returns a tuple of all files chosen, not the strange string with curly braces anymore (must have been fixed).

Oddly, if the cancel button is pressed or the user exits out of the browse window, an empty string is returned instead of an empty list or tuple. Luckily for us Python recognizes strings as iterable objects, meaning you can still check if len(filedialog.askopenfilenames()) == 0.

Share:
11,433
Paul
Author by

Paul

Background is in physical chemistry and NMR instrumentation, now working as a software developer.

Updated on July 18, 2022

Comments

  • Paul
    Paul almost 2 years

    I'm trying to get a list of filenames from tkinter.filedialog.askopenfilenames() in Python 3.2.

        files = askopenfilenames(initialdir="C:\\Users\\BVCAP\\Videos", title="Select files")
        self.num_files.set(len(files))  
    

    I was expecting the output to be a tuple (or maybe a list) with each element containing a filename. As far as I can tell, it's returning a string with each element contained within curly-brackets {} like so:

    {C:\Users\BVCAP\File1.txt} {C:\Users\BVCAP\File2.txt}

    This is what I get if I try print(files). It looks like it's formatted like a list of some sort, but it seems to just be a string. Am I doing something wrong, or is the output of this function actually a string formatted like a list of files, which I need to split up by myself.