自学内容网 自学内容网

python 解决问题,跨目录引用py文件方法找不到路径

执行代码报错,找不到文件路径 

 报错信息

Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\pythonProject40\case\1\22\test_case_file.py", line 3, in <module>
    data = yam_util.read_yaml()
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\pythonProject40\comm\yam_util.py", line 13, in read_yaml
    with open('conf.yaml', encoding='UTF-8') as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'conf.yaml'

进程已结束,退出代码1

解决办法

import os


# 获取当前文件所在目录的绝对路径
current_path = os.path.abspath(__file__)
# 获取项目根目录的绝对路径
project_root = os.path.dirname(os.path.dirname(current_path))

print(project_root)

import yaml
import os


# 获取当前文件所在目录的绝对路径
current_path = os.path.abspath(__file__)
# 获取项目根目录的绝对路径
project_root = os.path.dirname(os.path.dirname(current_path))


def read_yaml():
    """
    读取yaml文件
    :return:
    """
    with open(project_root +r'\comm\conf.yaml', encoding='UTF-8') as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
        return data


if __name__ == '__main__':
    print(project_root)
    print(read_yaml())

 


原文地址:https://blog.csdn.net/qq_26086231/article/details/135468883

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!