Python获取python文件所在目录

如何获取python文件所在绝对路径,目录,以及父目录?并在代码中引用是一个非常重要的主题。以下分享示例:

该python代码路径为:/home/lab/filepath.py


```python
import os
#文件绝对路径
file_path_and_name = os.path.abspath(__file__)
print (">>>>> 1. The file full path:   os.path.abspath(__file__) path is:                                      ", file_path_and_name)

#文件所在目录
file_full_path = os.path.dirname(os.path.abspath(__file__))
print (">>>>> 2. The file folder path: os.path.dirname(os.path.abspath(__file__)) path is:                     ", file_full_path)

#文件目录的父目录
file_full_path_up =  os.path.dirname( os.path.dirname(os.path.abspath(__file__)))
print (">>>>> 3. The file folder up path: os.path.dirname( os.path.dirname(os.path.abspath(__file__))) path is:", file_full_path_up)

# 通过本文件所在目录,构造子目录
template_path = os.path.join(file_full_path, "template")
print (">>>>> 4. The sub folder path:  os.path.join(os.path.dirname(os.path.abspath(__file__)), 'template'):   ", template_path)
~                                                                                                                                   
结果:

```python
lab@ubuntu:/tmp$ python3 /home/lab/filepath.py
>>>>> 1. The file full path:   os.path.abspath(__file__) path is:                                       /home/lab/filepath.py
>>>>> 2. The file folder path: os.path.dirname(os.path.abspath(__file__)) path is:                      /home/lab
>>>>> 3. The file folder up path: os.path.dirname( os.path.dirname(os.path.abspath(__file__))) path is: /home
>>>>> 4. The sub folder path:  os.path.join(os.path.dirname(os.path.abspath(__file__)), 'template'):    /home/lab/template
    原文作者:fuyouhan
    原文地址: https://blog.csdn.net/fuyouhan/article/details/121877971
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞