【问题标题】:How to add a relative path in python to find image and other file with a short path?如何在python中添加相对路径以查找具有短路径的图像和其他文件?
【发布时间】:2016-07-28 08:42:49
【问题描述】:

我的项目文件夹排列方式如下:

Project folder-> Program folder->program
              -> Image folder named images->image

现在当我尝试在我的程序中处理路径为images/image1.png 的图像时? 发生错误。 可以在python中添加相对路径来查找短路径images/image1.png的图片吗?

我不想将我的图像文件夹移动到程序文件夹中,也不想通过../images/image1.png更改路径?

【问题讨论】:

    标签: python path relative-path


    【解决方案1】:
    import os
    script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
    rel_path = "../images/image1.png"
    abs_file_path = os.path.join(script_dir, rel_path)
    

    现在您可以使用 abs_file_path 变量作为图像的路径

    import os
    script_dir = os.path.dirname(__file__)
    rel_path = "../images/"
    abs_file_path = os.path.join(script_dir, rel_path)
    current_file ="image" + str(X) +".png"
    file = open(abs_file_path+current_file,'r')
    

    【讨论】:

    • 感谢您的回答。修改后,我的程序可以通过'images/image1.png'找到image1.png,但是,名为images的文件夹中有很多图像,有没有什么办法可以让'images/imagex.png'
    • @XiangweiWang 如果你喜欢这个答案,请按对勾
    • @joelgoldstick 我不确定,但我认为他永远不会接受这个答案作为解决方案:)
    • 这不是最好的解决方案,这不包括从其他脚本导入该脚本的情况。
    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多