File Open Dialog Box in Python

I’m putting the finishing touches on a side project at work that requires opening a file as an argument at the command line, or through a file open dialog box. Here’s a snippet that demonstrates how I implemented it.

 

import sys
import os

def choose_file():
    try:
        import Tkinter, tkFileDialog
    except ImportError:
        print "Tkinter not installed."
        exit()
    
    #Suppress the Tkinter root window
    tkroot = Tkinter.Tk()
    tkroot.withdraw()
    
    return str(tkFileDialog.askopenfilename())
    
if __name__ == "__main__":
    
    #If no file is passed at the command line, or if the file
    #passed can not be found, open a file chooser window.
    if len(sys.argv) < 2:
        filename = os.path.abspath(choose_file())
    else:
        filename = os.path.abspath(sys.argv[1])
        if not os.path.isfile(filename):
            filename = choose_file()
            
    #Now you have a valid file in filename

It’s pretty straightforward. If no file is passed at the command line, or if the file passed at the command line isn’t a legitimate file, a file chooser dialog box pops up. If Tkinter isn’t installed, it bails out with an error message.

The bit about suppressing the Tk root window prevents a small box from appearing alongside the file chooser dialog box.

 

This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s