从其他fi中的不同目录导入文件

2024-06-25 22:58:58 发布

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

我是python新手,一直在尝试导入位于不同文件中的函数。你知道吗

我的文件树如下所示

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

你知道吗公共功能.py位于主目录中,我想使用公共功能.py在file1.py中

我的公共功能.py有以下代码

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

我想使用file1.py中的setUp函数

我试过进口,但没用,真的很感谢你的帮助。 仅供参考,我正在使用Python2.7


Tags: 文件函数代码py功能setupunittesttestcase
1条回答
网友
1楼 · 发布于 2024-06-25 22:58:58

使用两个点向上指定一个目录(一个点表示当前目录而不是python路径):

from ..CommonFunctions import random_func

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. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod.

请记住,您可以像这样附加到系统路径:

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

import file

相关问题 更多 >