Python 解决相对路径问题:"No such file or directory" 您所在的位置:网站首页 python相对路径打开文件选择什么 Python 解决相对路径问题:"No such file or directory"

Python 解决相对路径问题:"No such file or directory"

2024-01-19 04:29| 来源: 网络整理| 查看: 265

如果你取相对路径不是在主文件里,可能就会有相对路径问题:”No such file or directory”。

因为 python 的相对路径,相对的都是主文件。

如下目录结构:

| -- main.py | -- conf.py | -- start.png | -- config.txt

main.py 是主文件。

conf.py 里引用 config.txt 用相对路径。

如果用 . 或 … 相对的是 main.py,所以用 “./config.txt”,相对于 main.py 是同一个目录下。

.指当前文件所在的文件夹,… 指当前文件的上一级目录。

补充知识:解决python模块调用时代码中使用相对路径访问的文件,提示文件不存在的问题

问题分析:

在编码过程中使用相对路径使代码的稳定性更好,即使项目目录发生变更,只要文件相对路径不变,代码依然可以稳定运行。但是在python代码中使用相对路径时会存在以下问题,示例代码结构如下:

其中test包中包含两个文件first.py和user_info.txt,first.py代码中只有一个函数read_file,用于读取user_info.txt文件第一行的内容,并打印结果,读取文件使用相对路径,代码如下:

import os print("当前路径 - %s" %os.getcwd()) def read_file() : with open("user_info.txt" , encoding = 'utf-8') as f_obj : content = f_obj.readline() print("文件内容 - %s" %content) if __name__ == '__main__' : read_file()

first.py程序代码执行结果如下:

当前路径 – E:\程序\python代码\PythonDataAnalysis\Demo\test 文件内容 – hello python !!!

与test在同一目录下存在一个second.py文件,在这个文件中调用first.py文件中的read_file方法读取user_info.txt文件,代码如下:

from test import first first.read_file()

second.py程序执行结果如下:

当前路径 – E:\程序\python代码\PythonDataAnalysis\Demo File “E:/程序/python代码/PythonDataAnalysis/Demo/second.py”, line 8, in



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有