0

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?

4

3 回答 3

1

imp 模块有两个函数一起工作以动态导入模块。

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()
于 2013-08-16T16:34:02.780 回答
1

添加__init__.py到文件夹,您可以将文件导入为from Files import *

于 2013-08-16T16:28:51.253 回答
0

如果要在运行时导入文件,请使用此功能:

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
于 2017-09-07T13:24:05.817 回答