【Python】:Python import导入上一级目录的文件和模块

假设我们想要导入上一级目录的文件或者模块,我们可以直接首先将环境变量添加到sys当中,sys这个模块包含了当前运行程序当中的所有运行环境变量,并保存在一个列表里,用sys.path可以对这个列表进行调用,因此

我们可以编写如下代码:

import sys
sys.path.insert(0,"the absolutely path of the file or the folder")

在insert函数后,有两个参数,第一个参数填0,表示在第一个位置对path进行插入,第二个参数填写你想要import 模块文件或者文件夹的绝对路径,这样你的模块就可以顺利import了!

比如你现在可以import 上级目录的config.py模块,如下所示:

import sys
sys.path.insert(0,"the absolutely path of the file or the folder")
import config

这样咱们再import config就不会报错啦!

pay attention!:这里值得注意的是,我们需要想要import 上级目录模块之前,首先使用sys.path.insert,然后再开始使用你想进行import的文件,因为我们需要先添加环境变量哦!

posted @ 2021-07-21 22:49  Geeksongs  阅读(2780)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.