1

I'm making a game engine that can be used with multiple story modules. I want to keep the stories in a subdirectory and use a single PLAY.py file to allow the user to choose one of them.

So far, I have been able to use this simple code to get a list of all of the story modules:

import glob
stories = glob.glob( ./stories/ds_*.py )

I then use a for loop and a format statement to list the options for the user. The problem is that I can't find out how to use the resulting strings to actually import anything. Maybe glob is not the best solution?

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
A B
  • 59
  • 6
  • Possible dup of http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – dhke Jun 23 '15 at 10:36

1 Answers1

2

Just list the files in the stories directory and then open the one the user selected:

from os import listdir
from os.path import isfile, join
import imp

stories_path = 'path/to/modules'

# Put in stories all the modules found:
stories = [f for f in listdir(stories_path ) if isfile(join(stories_path,f))]

# Let the user select one...
selected = stories[xx]

# Import it:
story = imp.load_source('module.name', selected)
Alex
  • 6,849
  • 6
  • 19
  • 36