0

I am writing a text-based Madlibs game in Python, but it has code separated into multiple scripts to make development easier.

I have already tried importing the required files using a for loop:

import os, importlib
   
foundStories = os.listdir('...madlibs/stories')
   
for story in foundStories:
  
    importlib.import_module(story)

I had to use importlib because the built-in import import apparently doesn't support passing in module names as a variable.

Every time I run the script I get these errors:

Traceback (most recent call last):
  File "Madlibs-v7-TEST.py", line 7, in <module>
    importlib.import_module(story)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'story3'

Should also mention that my 'story files' are just ordinary Python scripts themselves, they are not 'Python modules' or anything.

Please try to keep answers simple and legible, as I am a beginner programmer.

I only program as a hobby, and have no interest in software development.

I'm guessing this has to do with a problem in my Python build and not my code at all.

For reference, my OS is: Ubuntu 20.04

MissBrae
  • 1
  • 2
  • 2
    What's wrong with explicitly importing the modules you need? What is the point of importing an unknown set of modules? You won't know what's in modules you don't know you're importing, so you wont be able to call or use anything in them without referring to them? – Grismar Feb 04 '22 at 04:43
  • I can't explicitly import the modules because they are dynamic. I want to be able to add-on 'story files' later on and have the main script automatically find them so they will be available to import by the user. That's the whole point of this project... – MissBrae Feb 06 '22 at 00:21
  • The problem with them being 'dynamic' is that you also can't really use them from your code, because you won't know what variables and function are in them. If you just view them as separate scripts to execute, you could easily do that with a subprocess. If you just view them as data to drive a story engine, you should look at defining them in json for example, and writing code to load and execute a generic story engine that runs on the data. – Grismar Feb 06 '22 at 00:38

0 Answers0