当前位置:首页 » python教程 » 正文

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

看: 1232次  时间:2020-06-25  分类 : python教程

如果你取相对路径不是在主文件里,可能就会有相对路径问题:"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

first.read_file()

File "E:\程序\python代码\PythonDataAnalysis\Demo\test\first.py", line 10, in read_file

with open("user_info.txt" , encoding = 'utf-8') as f_obj :

FileNotFoundError: [Errno 2] No such fileor directory: 'user_info.txt'

以上信息提示user_info.txt 文件不存在,查看os.getcwd() 函数输出的当前路径会发现,当前路径是 XXX/Demo,而不是上一次单独执行first.py 文件时的 XXX/Demo/test了,所以程序报错文件不存在的根本原因是因为当前路径变了,导致代码中的由相对路径构成的绝对路径发生了变化。

解决方法:

对于这种问题,只需要在使用相对路径进行文件访问的模块中加入以下代码即可(加粗内容),修改后的first.py代码如下:

import os
print("当前路径 -> %s" %os.getcwd())
current_path = os.path.dirname(__file__)
def read_file() :
  with open(current_path + "/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

current_path -> E:/程序/python代码/PythonDataAnalysis/Demo/test

文件内容 -> hello python !!!

second.py代码不变,second.py代码执行结果如下:

当前路径 -> E:\程序\python代码\PythonDataAnalysis\Demo

current_path -> E:\程序\python代码\PythonDataAnalysis\Demo\test

文件内容 -> hello python !!!

由以上执行结果可以发现,虽然first.py和second.py代码执行时os.getcwd()函数的输出结果还是不一致,但是current_path = os.path.dirname(__file__)

代码得到的current_path路径是相同的,current_path就是first.py文件所处的路径,然后再由current_path 和user_info.txt 组成的文件绝对路径则是固定的,这样就可以确保在进行模块导入时,模块中使用相对路径进行访问的文件不会出错。

以上这篇Python 解决相对路径问题:"No such file or directory"就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!