简体   繁体   English

在Python中获取绝对路径

[英]Get absolute path in Python

I'm having a problem with assigning static files containing resources. 我在分配包含资源的静态文件时遇到问题。

My working directory structure is: 我的工作目录结构是:

|- README.md
|- nlp
|   |-- morpheme
|   |-- |-- morpheme_builder.py
|   |-- fsa_setup.py
| - tests
|   |-- test_fsa.py
| - res
|   |-- suffixes.xml

The code for fsa_setup.py is: fsa_setup.py的代码是:

class FSASetup():
    fsa = None
    def get_suffixes():
        list_suffix = list()
        file = os.path.realpath("../res/suffixes.xml")
        .....
if __name__ == "__main__":
    FSASetup.get_suffixes()

The code for morpheme_builder.py is: morpheme_builder.py的代码为:

class MorphemeBuilder:
    def get_all_words_from_fsa(self):
        ......
if __name__ == "__main__":
    FSASetup.get_suffixes()

When it is called in fsa_setup.py , the file path's value is '\\res\\suffixes.xml' and that is correct, but when the other case realized, the file path value is '\\nlp\\res\\suffixes.xml'. fsa_setup.py中调用该文件时,文件路径的值为'\\ res \\ suffixes.xml',这是正确的;但是在另一种情况下,文件路径的值为'\\ nlp \\ res \\ suffixes.xml'。

I know how it works like this. 我知道它是如何工作的。 So how can I give the path of the resource to the file . 因此,如何将资源的路径提供给文件

The problem is that morpheme_builder.py is in the directory morphem . 问题是morpheme_builder.py在目录morphem So when you say ../res/suffixes.xml it will go on directory back ... so it will go to nlp/res/suffixes.xml . 因此,当您说../res/suffixes.xml ,它将放在目录的后面...因此它将转到nlp/res/suffixes.xml What about if you use os.path.abspath("../res/suffixes.xml") ? 如果使用os.path.abspath("../res/suffixes.xml")怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM