简体   繁体   English

如何从python中的特定文件夹导入几个文件

[英]How to import several files from specific folder in python

I am new to Python and have a problem that I don't know how to solve 我是Python新手,有一个我不知道如何解决的问题

I need to write a module (directory C:/Python ) that is able to import and execute all .py files that are located in some other folder (for example C:/Python/Dir ). 我需要编写一个模块(目录C:/Python ),该模块能够导入和执行位于其他文件夹(例如C:/Python/Dir )中的所有.py文件。 I know how to access to directory ( sys.path.append('C:\\\\Python26\\\\Dir') ) but how do I make a loop that is able to import all .py files from this folder? 我知道如何访问目录( sys.path.append('C:\\\\Python26\\\\Dir') ),但是如何制作一个循环,该循环能够从该文件夹中导入所有.py文件?

You should really use the __import__ built-in function together with glob : 您确实应该将__import__内置函数与glob一起使用:

os.chdir(path)
for file in glob.glob('*.py')
    __import__(file[:-2])

If you import all the files in a directory by some glob, how could you access these modules contents without a name? 如果通过某个glob将目录中的所有文件导入,那么如何在没有名称的情况下访问这些模块的内容? Maybe there is a way to get all imported modules even if they're anonymous (see Return a list of imported Python modules used in a script? - not an easy task), but isn't it easier to list them explicitly? 也许有一种方法可以获取所有导入的模块,即使它们是匿名的(请参阅返回脚本中使用的导入的Python模块的列表? -并非易事),但是显式列出它们是否更容易?

Maybe you can just create some __init__.py file in your directory and explicitly list imported files there with appropriate module names. 也许您可以只在目录中创建__init__.py文件,并在其中显式列出带有适当模块名称的导入文件。

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

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