如何获得跨平台绝对相对文件路径?

时间:2017-04-20 12:01:01

标签: python operating-system

我在通过Windows(本地测试和开发)和Linux(CI CD)运行的代码上通过路径加载文件时遇到问题。

在Windows中本地运行我的代码时,文件路径相对工作正常,当我的代码在Linux上运行时,它变成一团糟并返回错误:No such file or directory

Python中是否有这样的代码可以解决它的跨平台?

我的代码是这样的:

def get_event_json_file_path(fileName):
    file_dir = os.path.dirname(os.path.realpath('__file__'))
    file_path = os.path.join(file_dir, "events/" + fileName)
    return file_path

是否有代码来获取文件夹的类路径?

1 个答案:

答案 0 :(得分:2)

我设法编写了这个函数:

def get_relative_file_path(file_dir_path, fileName):
    dir = os.path.dirname(__file__)
    file_path = os.path.join(dir, file_dir_path,fileName)
    return file_path

用法:

get_relative_file_path('../resources/', "restCallBodySchema.json")
相关问题