python调用文件时找不到相对路径的解决方案
作者:Channing 时间:2021-08-21 14:38:24
python调用文件时找不到相对路径
current_path = os.path.dirname(__file__)
if current_path=='':
sys.path.append(sys.path[0]+'/..')
else:
sys.path.append(current_path+'/..')
解释:
current_path = os.path.dirname(__file__)
#寻找当前文件的绝对路径
if current_path=='':
#当直接用python xx.py执行该文件时添加绝对路径sys.path[0](此时current_path为空)
sys.path.append(sys.path[0]+'/..')#以寻找上一级目录为例,可以自己修改
else:
#当调用该.py文件时,取current_path(此时为绝对路径)
sys.path.append(current_path+'/..')
python相对路径问题
最近在调试代码时候遇到了相对路径上的问题,测试的代码结构录下。
代码与读入的图像文件不在同一级目录,当我直接运行main.py代码的时候会提示找不到10.png文件。
当在terminal窗口中在与图像文件同一级的目录执行python code/main.py时运行成功,能够找到文件并成功执行代码。
由此可以得出一个结论,相对路径的相对位置是程序运行的位置,而不是文件存在的位置,那么想要解决这个问题,只需要设置一下程序的工作路径即可。
此时能够根据文件目录找到相对路径的位置。
来源:https://blog.csdn.net/lycwhu/article/details/120166312
标签:python,调用文件,相对路径
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
GO语言中接口和接口型函数的具体使用
2023-06-18 09:08:40
根据对象的某一属性进行排序的js代码(如:name,age)
2023-08-31 14:05:43
如何读取一个.ini文件?
2009-11-18 20:58:00
PyQt5每天必学之拖放事件
2021-02-28 19:26:15
![](https://img.aspxhome.com/file/2023/1/97191_0s.png)
深入了解python的tkinter实现简单登录
2023-03-25 14:15:27
![](https://img.aspxhome.com/file/2023/4/95514_0s.png)
python实现批量转换文件编码(批转换编码示例)
2023-07-28 22:03:47
Python+PyQT5的子线程更新UI界面的实例
2022-06-09 10:39:02
Python重试库 Tenacity详解(推荐)
2021-07-07 00:20:09
![](https://img.aspxhome.com/file/2023/2/103202_0s.png)
教你利用python实现企业微信发送消息
2023-09-06 11:20:55
![](https://img.aspxhome.com/file/2023/2/105052_0s.png)
Python (Win)readline和tab补全的安装方法
2021-07-30 16:04:46
![](https://img.aspxhome.com/file/2023/5/76965_0s.jpg)
利用Pycharm将python文件打包为exe文件的超详细教程(附带设置文件图标)
2021-12-06 18:06:24
![](https://img.aspxhome.com/file/2023/8/93888_0s.png)
如何用Python画一些简单形状你知道吗
2021-06-23 06:56:13
![](https://img.aspxhome.com/file/2023/0/112920_0s.png)
Python第三方库face_recognition在windows上的安装过程
2023-07-27 02:51:29
一个比较完美的spacer div技巧
2009-03-18 19:29:00
Webpack4 使用Babel处理ES6语法的方法示例
2023-08-30 08:12:37
![](https://img.aspxhome.com/file/2023/8/56198_0s.png)
python常用模块详解
2021-05-24 05:16:55
![](https://img.aspxhome.com/file/2023/0/95700_0s.png)
Python调用腾讯云短信服务发送手机短信
2021-10-07 16:55:38
![](https://img.aspxhome.com/file/2023/2/112122_0s.png)
Python输出指定字符串的方法
2023-07-29 15:06:02
基于pytorch的lstm参数使用详解
2023-11-21 08:41:21
![](https://img.aspxhome.com/file/2023/9/87709_0s.jpg)
如何修复MySQL数据库表
2009-03-20 13:24:00