Specify File path in tkinter File dialog

manateejoe picture manateejoe · Jun 29, 2015 · Viewed 7.9k times · Source

I have a file dialog to open a file, however, the file that I want to open is in a different directory than the program I wrote. The file dialog opens to the directory where I am. Is there a way to specify where the filedialog opens?

Here is the relevant code:

root = Tk()
root.fileName = tkFileDialog.askopenfilename()
f = open(root.fileName, 'r')

I tried adding the path that I want into the "askopenfilename" call, but that didn't work:

root.fileName = tkFileDialog.askopenfilename('/C:')

Answer

maccartm picture maccartm · Jun 29, 2015

What you want is:

root.fileName = tkFileDialog.askopenfilename(initialdir = "C:/<whatever>")

This argument will allow you to specify the directory to which the window will open up.