简体   繁体   English

从另一个文件中的其他目录导入文件

[英]Importing file from a different directory in another file

I am new to python and have been trying to import a function that lies in a different file. 我是python的新手,并一直在尝试导入一个位于不同文件中的函数。

My file tree is like below 我的文件树如下所示

MainDir 
  ->folder1
     ->file1.py
 ->CommonFunctions.py

CommonFunctions.py lies in the main directory and I want to use the functions of CommonFunctions.py in file1.py CommonFunctions.py位于主目录中,我想在file1.py中使用CommonFunctions.py的功能

My CommonFunction.py has below code 我的CommonFunction.py有以下代码

class CommonFunctions(unittest.TestCase):
    def setUp(self):
            logging.info('CALLED')

I want to use the setUp function from file1.py 我想使用file1.py中的setUp函数

I have tried imports but thats not working, any help really appreciated. 我尝试过进口,但那不起作用,任何帮助都非常感激。 FYI, am using Python 2.7 仅供参考,我正在使用Python 2.7

Use two dots to specify one directory up (one dot would mean current directory instead of python path): 使用两个点指定一个目录(一个点表示当前目录而不是python路径):

from ..CommonFunctions import random_func

From PEP 328 : PEP 328

One leading dot means the current package where the module making the import exists. 一个前导点表示存在导入模块的当前包。 Two dots means up one package level. 两个点表示一个包级别。 Three dots is up two levels, etc. So if you execute from . 三个点是两个级别,等等。所以如果你执行。 import mod from a module in the pkg package then you will end up importing pkg.mod. 从pkg包中的模块导入mod,然后您将最终导入pkg.mod。 If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. 如果从pkg.subpkg1中的..subpkg2 import mod执行,则将导入pkg.subpkg2.mod。

Remember that you can always append to system path like so: 请记住,您始终可以像这样附加到系统路径:

import sys
sys.path.insert(0, '/path/to/file')

import file

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

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