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

2024-10-03 15:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录中有大约50个Python文件,它们都是按顺序命名的,例如:myfile1myfile2…..myfile50。现在,我想将这些文件的内容导入另一个Python文件中。这就是我所尝试的:

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

但是,我得到了以下错误:

^{pr2}$

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


Tags: 文件nameimport目录内容顺序错误myfile
3条回答

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

导入importlib

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

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

^{pr2}$

@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", "") )

other answer by @Mureinik很好,但是仅仅做-importlib.import_module(file_name)是不够的。如the documentation of ^{}-

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只返回module对象,它不会将其插入到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()字典(这是全局命名空间的字典)。示例-

^{pr2}$

如果ImportError不存在ImportError模块,那么最好是将它们排除在外,您可以根据需要处理它们。在

相关问题 更多 >