简体   繁体   English

Python:如何迭代文件名列表并导入它们?

[英]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. 假设我有一个名为“Files”的文件夹,其中包含许多不同的python文件。

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". 这给了我一个列表,其中包含“Files”文件夹中所有python文件的名称。

I want to import each one of these files into a larger python program, one at a time, as a module. 我想将这些文件中的每一个导入一个更大的python程序,一次一个,作为一个模块。 What is the best way to do this? 做这个的最好方式是什么?

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

The imp module has two functions that work together to dynmically import a module. 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()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM