【问题标题】:Relative address in python [duplicate]python中的相对地址[重复]
【发布时间】:2020-12-07 08:51:44
【问题描述】:

参考这里的问题Relative paths in Python。我也有类似的问题。

我的项目结构:

proj
 |
 |--config
 |    |--ENV
 |
 |--folder1
 |    |--UI
 |       |--test2.py 
 |
 |--test1.py

我想使用 test1.py 和 test2.py 访问 ENV 文件,但我要使用相对地址,这样我每次移动项目时都不必更改代码。

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'config/ENV')

上面的代码在 test1.py 中运行良好,但在 test2.py 中失败,因为现在 dirname 已更改。

我正在寻找可以在这两个文件上使用的代码。目前我只有一个想法是在\的基础上拆分地址找到proj并附加config/ENV有没有更好更干净的方法?

C:\Users\User1\proj\config/ENV  -- at test1.py

C:\Users\User1\proj\folder1\UI\config/ENV  --  at test2.py

我目前的解决方案:

dirname = os.path.dirname(__file__)
PROJECT_NAME = "proj"
x = dirname[:dirname.find(PROJECT_NAME) + len(PROJECT_NAME)]
filename = os.path.join(x, 'config/ENV')

【问题讨论】:

  • @spectras 链接建议在我的情况下使用不同的路径(使用../..)我每次尝试从不同的入口点访问 ENV 文件时都必须更改代码,因为我的项目有多个入口点。
  • 您将使用__file__ 技术来获取项目根目录的完整路径。从那里你可以添加你的路径,总是一样的。

标签: python python-3.x


【解决方案1】:
My Project
    some_file.py

    Resources
        bg.png
        music.mp3

    Folder
        another_file.py

如果你想从 some_file.py 访问你的资源,相对路径应该是 ./Resources/... 但如果你想使用来自 another_file.py 的资源,你会做../Resources/...

所以在你的情况下,如果你想从 test1.py 访问 ENV 文件,它的相对位置将是./config/ENV,但如果你想从test2.py,它的相对位置是../../config/ENV

记住../表示上一层,./表示同一层。

修改:
这里有固定路径config/ENV。在relative_path() 中传递该固定路径会为您提供相对路径地址。

# proj
#   config
#     ENV
#
#   folder1
#     config
#       some_other_file.txt
#
#     UI
#       test2.py
# 
#   test1.py


import os

def relative_path(path):
    # Get the parent directory of the
    # file that you need the relative
    # path for.
    my_dir = path.split('/')[0]
    
    # Recursively match the directory
    # in the given path. if the match
    # not found go up one level.
    def match_dir(c_path):
        c_path = os.path.split(c_path)[0]
        
        if my_dir in os.listdir(c_path) and (
            os.path.isfile(
                os.path.join(c_path, path)
            )
        ):
            # this whole if-block can be omitted
            # if the folder you're trying to access
            # is on the same level, this just prepends
            # with './'. I added this just for
            # aesthetic reason.
            if os.path.basename(__file__) in os.listdir(c_path):
                return './' + path
                
            return path
            
        return "../" + match_dir(c_path)
    
    
    return match_dir(
        os.path.realpath(__file__)
    )


# Getting relative path from test2.py
print(relative_path("config/ENV"))
print(relative_path("config/some_other_file.txt"))

# Try running this from test1.py
print(relative_path("config/ENV")) # './config/ENV'

这不是很优化。只是一个大概的想法。

【讨论】:

  • 是的,我知道,但我想在文件 test1 和 test2 上运行相同的代码
  • 实际上我的项目中有多个入口点,ENV 需要读取一次,所以我正在寻找可以工作的代码,无论是主文件还是启动文件是
  • 如果您想从两个文件中获取相同的相对地址,那么我认为这是不可能的。 test2.py 向下两级。也许您可以在从 test2.py 访问 ENV 文件时动态添加 ../../
  • 是的,我认为每次我都必须预处理基址。
  • @anoop 抱歉,我知道已经晚了。我有一些工作。所以我编辑了我的答案。让我知道这是否有帮助。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2013-12-06
  • 1970-01-01
  • 2021-10-30
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多