python项目中如何导入不同文件夹下的文件

1、两个文件在同级目录,first.py和second.py 

second.py内容为:

import numpy 
import pandas

def hello():
    print("hello")

在first.py中调用second.py中的hello函数

import sys
import os

import second as second



second.hello()

2.second.py在first.py的子目录

文件结构如下:

还是同样的需求,first需要调用second中的hello函数

second.py函数

import numpy 
import pandas

def hello():
    print("hello")

first.py函数内容

import sys
import os

import test2.second as second


second.hello()

3.second是在first的父目录下

second函数内容

import numpy 
import pandas

def hello():
    print("hello")

first函数内容

import sys
import os
# 将test2下面的目录加载系统环境中,其中os.path.dirname()是获得当前文件的父目录
# 并将其加载到环境变量中 (注:这种环境变量只在运行时生效,程序运行结束即失效)
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import second as second


# print(os.path.dirname(os.path.dirname(__file__)))
second.hello()

以上的sys.path是一个列表,打印结果如下图所示,里面存储了各种环境变量,其中sys.path[0]存储了当前文件的位置,可以直接通过sys.path[0]获取本文件所在的绝对路径

关于os.path.dirname()以及参数__file__和sys.path的介绍(注:如果在py中使用,直接使用__file__即可,但是如果在ipynb中使用的话,使用的格式为"__file__",需要加上双引号

jupyter 内使用的代码如下:

print(os.path.abspath("__file__"))
print(os.path.abspath("."))

),这里贴出一张stackoverflow的精彩回答

加入下面的这句话,python就可以找到我们在first.py中导入的second.py文件,程序可以正常运行

sys.path.append(os.path.dirname(os.path.dirname(__file__)))

4.对于跨文件的py文件调用

文件目录结构如下

second函数内容

import numpy 
import pandas

def hello():
    print("hello")

first函数内容

import sys
import os
# 此处os.path.dirname()可以获得上一级目录,也就是当前文件或文件夹的父目录
# 将目录加入到sys.path即可生效,可以帮助python定位到文件(注:这种方法仅在运行时生效,不会对环境造成污染)
sys.path.append(os.path.dirname(os.path.dirname(__file__)))


import test2.second as second


# print(os.path.dirname(os.path.dirname(__file__)))
second.hello()

跨文件夹调用与第三种问题类似,只需要把相应的代码目录加入到sys.path中去,python在运行的时候,可以精准定位到想要导入的文件

附:对于找不到module的情况,还可以使用os.getcwd()获得当前路径,在py文件中进行字符串拼接,拼接出完整的绝对路径,打开或者访问绝对路径即可找到文件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值