1

I've written a couple of simple command line/terminal Python programs to parse the data files from the experiment-running software we use in our psychology lab. The programs are going to be used by people who are generally computer savvy, but not necessarily up to speed with full-blown unix style commands with flags, so I generally just have the program ask questions like "Which file do you want to process?" and have the user pick from a list, like this:

import textwrap
import os
import sys

def get_folder():
    """ Print a numbered
    list of the subfolders in the working directory
    (i.e. the directory the
    script is run from),
    and returns the directory
    the user chooses.
    """
    print(textwrap.dedent(
    """
    Which folder are your files located in?
    If you cannot see it in this list, you need
    to copy the folder containing them to the
    same folder as this script.
    """
    )
    )
    dirs = [d for d in os.listdir() if os.path.isdir(d)] + ['EXIT']
    dir_dict = {ind: value for ind, value in enumerate(dirs)}
    for key in dir_dict:
        print('(' + str(key) + ') ' + dir_dict[key])
    print()
    resp = int(input())
    if dir_dict[resp] == 'EXIT':
        sys.exit()
    else:
        return dir_dict[resp] 

Are there any implementations of these kinds of file choosers floating around in Python libraries? I've generally just been quickly implementing them myself whenever I need one, but I just end up having to copy and paste the code from file to file and modify for the specific case I'm using them for.

Marius
  • 58,213
  • 16
  • 107
  • 105
  • 2
    You could open a file dialog. Some ideas [here](http://stackoverflow.com/questions/9319317/quick-and-easy-file-dialog-in-python). – David Nov 13 '12 at 01:47
  • If you are copying and pasting this kind of code around to multiple files, you can probably think of a way to build it into your own reusable library that you just import for each specific use case. – TJD Nov 13 '12 at 01:47
  • @David Thanks, I was worried about adding a lot of GUI-related fiddliness to what's otherwise some pretty simple code, but `tkFileDialog` looks pretty simple. – Marius Nov 13 '12 at 01:50

0 Answers0