假设我们想要导入上一级目录的文件或者模块,我们可以直接首先将环境变量添加到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的文件,因为我们需要先添加环境变量哦!

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/geeksongs/p/15041991.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!