zoukankan      html  css  js  c++  java
  • 【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的文件,因为我们需要先添加环境变量哦!

  • 相关阅读:
    HDU1266 Reverse Number
    codevs1380 没有上司的舞会
    codevs1163 访问艺术馆
    codevs2144 砝码称重 2
    codevs1553 互斥的数
    codevs1230 元素查找
    codevs3118 高精度练习之除法
    codevs1245 最小的N个和
    codevs1063 合并果子
    codevs1052 地鼠游戏
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15041991.html
Copyright © 2011-2022 走看看