解决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 <module>

   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 组成的文件绝对路径则是固定的,这样就可以确保在进行模块导入时,模块中使用相对路径进行访问的文件不会出错。

参考内容来源

猜你喜欢

转载自blog.csdn.net/cxx654/article/details/79371565
今日推荐