Last used directory?

M

Michael Yanowitz

Hello:

Is there a global or some trick I can use to have
Python remember the last directory visited?
What I mean is suppose I have this function:

def get_filename():
""" Returns a filename selected from a Tkinter File Selection Dialog """
strFilename = tkFileDialog.askopenfilename(initialdir='.',
filetypes=[('Python
files','*.py'),
('All
Files','*.*')])
return strFilename

but instead of having initialdir='.' (current directory), I
would like it set to the last visited directory, which can be from a
previous run or even a previous day. Is that possible? If so how?


Thanks in advance:
Michael Yanowitz
 
S

Steven D'Aprano

but instead of having initialdir='.' (current directory), I
would like it set to the last visited directory, which can be from a
previous run or even a previous day. Is that possible? If so how?

Every time you open a file, save the directory in a global variable. Then
instead of passing '.' as initialdir, pass that saved directory.

That will work while you're in the same session. To remember the last
visited directory from one session to the next, you'll need to write it to
some sort of permanent storage like a configuration file.

You'll also need to check what happens if the saved directory no longer
exists.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top