python3 如何 獲取一個文件的目錄,獲取 上一級目錄
1 _file_ 是什麼 ?
# hello.py
if __name__ == '__main__':
file = __file__
print(f"file = {__file__!r}")
結果如下
file = ‘C:/Users/changfx/PycharmProjects/FirstDemo/demo/second_package/hello.py’
結果 是打印 file 的 路徑
# -*- coding: utf-8 -*-
"""
# 看下 __file__ 這個變量的含義 ,
https://docs.python.org/3/reference/datamodel.html
__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.
The __file__ attribute may be missing for certain types of modules,
such as C modules that are statically linked into the interpreter;
for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
"""
說明:
在 python 中 __file__ 是一個文件路徑, 當 一個python 模塊 被加載的時候, 它是從file load 進來的。
它是一個屬性。 它是一個特殊的屬性,這個屬性就代表了 這個文件的路徑。
按照官方文檔的方法,這個 __file__ 屬性 有可能 沒有對於 某些特定的模塊類型, 比如說 C 模塊,它是直接 鏈接到解釋器 。
對於從共享庫動態加載的擴展模塊,它是共享庫文件的路徑名。
from os.path import dirname
path = "C:/Users/changfx/PycharmProjects/FirstDemo/demo/second_package/hello.py"
print(dirname(path))
print(dirname(dirname(path)))
print(dirname(dirname(dirname(path))))
print(dirname(dirname(dirname(dirname(path)))))
從這裏 就可以 獲取 不同的目錄 ,dirname 就可以拿到當前 文件所在的目錄 , 多次使用 就可以 繼續 拿到 上一級 目錄 。
結果如下:
import os
from os.path import dirname
def get_path():
print('=== file ===')
print(__file__)
print('\n===獲取當前目錄 ===')
print(os.path.abspath(dirname(__file__)))
print("\n ===獲取 當前文件的 上一級目錄 === ")
# get package dir
package_dir = os.path.abspath(dirname(dirname(__file__)))
print(package_dir)
print("\n ===獲取 當前文件的 上上一級目錄 === ")
# print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
print(os.path.abspath(dirname(dirname(dirname(__file__)))))
結果如下圖:
2 如何獲取文件的目錄
如何獲取文件的目錄 以及 上一級目錄,上上一級目錄
可以封裝幾個函數 來獲取 這些文件路徑 。
還是以這個項目結構 爲例, 寫一個 hello.py
# -*- coding: utf-8 -*-
# hello.py
from os.path import dirname
from os.path import abspath
def get_current_dir():
"""
獲取 當前文件所在 目錄
:return:
"""
return abspath(dirname(__file__))
pass
def get_parent_dir():
"""
獲取當前 文件的 目錄 的 上一級 目錄
:return:
"""
pass
return abspath(dirname(dirname(__file__)))
def get_double_parent_dir():
"""
獲取當前 文件的目錄 的 上一級 目錄 的 父目錄
:return:
"""
pass
return abspath(dirname(dirname(dirname(__file__))))
if __name__ == '__main__':
print(get_current_dir())
print(get_parent_dir())
print(get_double_parent_dir())
結果如下:
參考文檔
stackoverflow https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do