Python for Power Systems

A blog for power systems engineers to learn Python.

Do You Want Files With That? Pop Up Dialog to Ask for PSSE Saved File

Pop up box ask for filename

Today we’ll write an example Python function to ask for filenames. You can use this function in your Python code to ask for saved case names or for output CSV file names.

Asking your users for the name of a saved case file using a pop up box is a nice touch. Though it isn’t the only way to to get filenames. Sometimes people hard code filenames into the Python script itself:

topsecret.py
1
2
3
4
if __name__ == "__main__":

    psspy.psseinit(8000)
    psspy.case(""c:/darryn/cases/2001 East Stages v43.sav"")

Here “Darryn” has put the saved case name at the very bottom of the file. Anyone wanting to run the code on another year’s case or with a different file version would need to read through the code and find this line to change it.

Another better strategy is to move the filename into its own variable near the top of the Python script or in a separate file called settings.py where all configurable aspects of your script should be collected:

topsecret.py
1
2
3
4
5
6
7
8
import psspy

#--------------------------
# Constants

SAVED_CASE = "c:/darryn/cases/2001 East Stages v43.sav"

#--------------------------

This is better, at least now the configurable portions of our program are in a predictable location for our colleagues to find. But we can do better, lets write a function to pop up a box asking the user which file they want to open.

Our pop up box will have a title, “Please select a saved case” and a file type filter: “Select a .sav file”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from tkFileDialog import askopenfilename, asksaveasfilename
import Tkinter
import tkFileDialog

#------------------------------------------------------------
# Exceptions

class NoFilenameSelected(Exception):
    """User didn't select a filename."""

#------------------------------------------------------------

def ask_for_filename(title=None, initialdir=None,
                                                filetypes=None, saveas=False):
    """
    Pop up a dialog box asking the user to select a file, 
    Returns the path of the file selected.

    Args:
      saveas - If True, use a save as dialog box and allow the user to select
               a file that does not yet exist. Otherwise the filename must
               already exist.
    raises:
        NoFilenameSelected - If the user presses cancel or 'X' quit on the
            dialog box.
    """
    if title is None: title = "Please select a file"
    if initialdir is None: initialdir = "."
    if filetypes is None: filetypes = [('all files', '*.*')]

    # hide the default root Tkinter window.
    root = Tkinter.Tk()
    root.withdraw()

    if saveas:
        askfunction = tkFileDialog.asksaveasfilename
    else:
        askfunction = tkFileDialog.askopenfilename

    fname = askfunction(title=title, initialdir=initialdir, filetypes=filetypes)
    if not fname:
        raise NoFilenameSelected(
                "User did not select a filename for '%s'" % title)
    return fname

#------------------------------------------------------------

if __name__ == "__main__":

    fname = ask_for_filename(
            title="Hi there",
            filetypes=[("pdf files", ".pdf")],
            saveas=True)
    print fname

Here are some examples using the new function:

1
2
3
4
5
6
7
8
9
10
11
# Only allow selecting .sav files.
>>> ask_for_filename(
 "Please select a PSSE Saved case",
  filetypes=[("Saved Case", ".sav")])
"C:/darryn/cases/2001 Eastern States High Demand case v43.sav"

>>> # Allow .csv and .txt files
>>> ask_for_filename(
 "Please select the output results file",
 filetypes=[("CSV", ".csv"), ("Text", ".txt")],
 saveas=True)

Next time you need to ask for a filename why not use the ask_for_filename function? It’ll pop up and brighten your day.