【问题标题】:Importing lists from multiple files从多个文件导入列表
【发布时间】:2016-08-27 07:35:48
【问题描述】:

在一个小项目中,我有以下路径结构:

main.py
Data---
      |
      __init__.py
      Actions_2016_01.py
      Actions_2016_02.py
      Actions_2016_03.py
      ... and so on...

每个“Action_date.py”文件都包含一个名为

的列表
data = [something_1, something_2, ...]

现在我正在尝试将“Action_date.py”文件的所有数据列表放到“main.py”文件中的单个列表中。

我尝试了类似的东西

files = os.listdir(os.path.join(os.path.dirname(__name__), 'Data'))
all_data = []
for name in files:
    if name.startswith('Actions'):
        import Data.name
        all_data.extend(name.data)

但这根本不起作用......我得到了

ImportError: No module named 'Data.name'

作为输出。

【问题讨论】:

    标签: python list python-3.x import


    【解决方案1】:

    我找到了解决方案。只需使用importlib 模块。

    【讨论】:

      【解决方案2】:

      您可以让您的 Data 包的 __init_.py 完成这项工作:

      def _import_modules():
          """ Dynamically import certain modules in the package, extract data in each
              of them, and store it in a module global named all_data.
          """
          from fnmatch import fnmatch
          import traceback
          import os
          global __all__
          __all__ = []
          global all_data
          all_data = []
          globals_, locals_ = globals(), locals()
      
          # dynamically import the desired package modules
          for filename in os.listdir(os.path.join(os.path.dirname(__name__), 'Data')):
              # process desired python files in directory
              if fnmatch(filename, 'Actions*.py'):
                  modulename = filename.split('.')[0]  # filename without extension
                  package_module = '.'.join([__name__, modulename])
                  try:
                      module = __import__(package_module, globals_, locals_, [modulename])
                  except:
                      traceback.print_exc()
                      raise
                  all_data.extend(module.data)
      
          __all__.append('all_data')
      
      _import_modules()
      

      这将允许您在main.py 中执行此操作:

      import Data
      
      print(Data.all_data)
      

      这是my answer对问题How to import members of modules within a package的改编?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 2016-06-23
        • 2018-05-06
        • 1970-01-01
        相关资源
        最近更新 更多