导入按顺序命名的多个文件 Python

Importing multiple files named sequentially in Python

我在一个目录下大约有50个Python个文件,都是按顺序命名的,例如:myfile1, myfile2.....myfile50 .现在,我想将这些文件的内容导入到另一个 Python 文件中。这是我试过的:

i = 0
while i < 51:
    file_name = 'myfile' + i
    import file_name
    i += 1

但是,我收到以下错误:

ImportError: No module named file_name

如何将所有这些按顺序命名的文件导入到另一个 Python 文件中,而不必为每个文件分别编写导入?

您不能使用 import 从包含模块名称的字符串中导入模块。但是,您可以使用 importlib:

导入 importlib

i = 0
while i < 51:
    file_name = 'myfile' + str(i)
    importlib.import_module(file_name)
    i += 1

另外,请注意 "pythonic" 迭代一定次数的方法是使用 for 循环:

for i in range(0, 51):
    file_name = 'myfile' + str(i)
    importlib.import_module(file_name)

is good, but simply doing - importlib.import_module(file_name) is not enough. As given in the documentation of importlib-

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned.

importlib.import_module 只是 returns 模块对象,它不会将它插入到 globals 命名空间中,所以即使你以这种方式导入模块,以后也不能使用它模块直接作为 filename1.<something>(左右)。

例子-

>>> import importlib
>>> importlib.import_module('a')
<module 'a' from '/path/to/a.py'>
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

为了能够通过指定名称来使用它,您需要将返回的模块添加到 globals() 字典(这是全局命名空间的字典)中。例子-

gbl = globals()
for i in range(0, 51):
    file_name = 'myfile{}'.format(i)
    try:
        gbl[file_name] = importlib.import_module(file_name)
    except ImportError:
        pass #Or handle the error when `file_name` module does not exist.

如果 file_name 模块不存在,除了 ImportError 可能会更好,您可以随意处理它们。

@Murenik 和@Anand S Kumar 已经给出了正确的答案,但我也只是想提供一点帮助 :) 如果你想从某个文件夹导入所有文件,最好使用 glob函数而不是硬编码 for 循环。它是 pythonic 遍历文件的方式。

# It's code from Anand S Kumar's solution
gbl = globals()
def force_import(module_name):
    try:
        gbl[module_name] = importlib.import_module(module_name)
    except ImportError:
        pass #Or handle the error when `module_name` module does not exist.

# Pythonic way to iterate files
import glob
for module_name in glob.glob("myfile*"):
    force_import( module_name.replace(".py", "") )