Kevin Vincent
Kevin Vincent

Reputation: 111

Python: How do you iterate over a list of filenames and import them?

Suppose I have a folder called "Files" which contains a number of different python files.

path = "C:\Python27\Files"
os.chdir(path)
filelist = os.listdir(path)
print(filelist)

This gives me a list containing the names of all of the python files in the folder "Files".

I want to import each one of these files into a larger python program, one at a time, as a module. What is the best way to do this?

Upvotes: 0

Views: 238

Answers (3)

Samer Abu Gahgah
Samer Abu Gahgah

Reputation: 741

if you want to import the files during runtime use this function:

def load_modules(filelist):
    modules = []
    for name in filelist:
        if name.endswith(".py"):
            name = os.path.splitext(name)[0]
            if name.isidentifier() and name not in sys.modules:
                try:
                    module = __import__(name)
                    modules.append(module)
                except (ImportError, SyntaxError) as err:
                    print(err)
    return modules

Upvotes: 0

Mayur Patel
Mayur Patel

Reputation: 1025

The imp module has two functions that work together to dynmically import a module.

import imp
import traceback
filelist = [os.path.splitext(x)[0] for x in filelist] # name of the module w/o extension
for f in filelist: # assume files in directory d
    fp, pathname, description = imp.find_module( f, [d])
    try:
        mod = imp.load_module(x, fp, pathname, description)        
    except:
        print(traceback.format_exc())
    finally:
        # must always close the file handle manually:
        if fp:
            fp.close()

Upvotes: 1

eri
eri

Reputation: 3504

add __init__.py to folder and you can import files as from Files import *

Upvotes: 1

Related Questions