Get a file's directory in a string selected by askopenfilename

Phoenix picture Phoenix · Dec 22, 2013 · Viewed 22.1k times · Source

I'm making a program that you use the askopenname file dialog to select a file, which I then want to save the directory to a string so I can use another function (which I already made) to extract the file to a different location that is predetermined. My button code that opens the file dialog is this:

`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`

Answer

user2555451 picture user2555451 · Dec 22, 2013

This should be what you want:

import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
    # Get the file
    file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
    # Split the filepath to get the directory
    directory = os.path.split(file)[0]
    print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()