Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing the results of askopenfilenames()?

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.

like image 224
Paul Avatar asked Nov 07 '10 02:11

Paul


2 Answers

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.

like image 93
Chris Collett Avatar answered Nov 16 '22 00:11

Chris Collett


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))
like image 44
eldarerathis Avatar answered Nov 16 '22 00:11

eldarerathis