Python獲取當前文件目錄的多種方法
更新時間:2026年01月21日 08:33:48 作者:mftang
文章介紹了在Python中獲取當前文件目錄的多種方法,包括基礎方法、使用__file__屬性、使用pathlib模塊(推薦于Python3.4+),并在不同場景下應用這些方法,此外,還討論了如何在模塊中獲取文件目錄、處理特殊場景以及構建路徑的實用函數(shù),需要的朋友可以參考下
概述
在 Python 中獲取當前文件目錄有多種方法,下面詳細介紹各種方式及其適用場景。
1. 基礎方法
import os
# 1. 獲取當前文件的絕對路徑
current_file_path = os.path.abspath(__file__)
print(f"當前文件的絕對路徑: {current_file_path}")
# 2. 獲取當前文件所在目錄
current_dir = os.path.dirname(current_file_path)
print(f"當前文件所在目錄: {current_dir}")
# 3. 直接獲取目錄(常用寫法)
current_directory = os.path.dirname(os.path.abspath(__file__))
print(f"當前目錄(常用寫法): {current_directory}")
# 4. 獲取當前工作目錄(可能不是文件所在目錄)
working_directory = os.getcwd()
print(f"當前工作目錄: {working_directory}")2. 使用__file__屬性
import os
# 1. 在不同環(huán)境下的表現(xiàn)
print(f"__file__ 屬性值: {__file__}")
# 2. 處理相對路徑
if not os.path.isabs(__file__):
# 如果是相對路徑,轉換為絕對路徑
abs_path = os.path.abspath(__file__)
print(f"轉換為絕對路徑: {abs_path}")
# 3. 獲取目錄的幾種方式
print("\n獲取目錄的不同方式:")
print(f"os.path.dirname(__file__): {os.path.dirname(__file__)}")
print(f"os.path.dirname(os.path.abspath(__file__)): {os.path.dirname(os.path.abspath(__file__))}")
# 4. 獲取父目錄的父目錄
parent_parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(f"父目錄的父目錄: {parent_parent_dir}")3. 使用pathlib模塊(Python 3.4+ 推薦)
from pathlib import Path
# 1. 獲取當前文件路徑
current_file = Path(__file__).resolve() # 解析為絕對路徑
print(f"Path對象: {current_file}")
print(f"當前文件路徑: {str(current_file)}")
# 2. 獲取當前文件所在目錄
current_dir = current_file.parent
print(f"目錄Path對象: {current_dir}")
print(f"目錄字符串: {str(current_dir)}")
# 3. 獲取父目錄
parent_dir = current_dir.parent
print(f"父目錄: {parent_dir}")
# 4. 獲取更多目錄信息
print("\n目錄詳細信息:")
print(f"目錄名稱: {current_dir.name}")
print(f"目錄的父目錄: {current_dir.parent}")
print(f"目錄的根目錄部分: {current_dir.anchor}")
print(f"目錄的所有父級: {list(current_dir.parents)}")
print(f"是否為絕對路徑: {current_dir.is_absolute()}")4. 不同場景下的應用
import os
import sys
from pathlib import Path
def get_current_directory():
"""獲取當前文件目錄的函數(shù)"""
# 方法1: 使用 os.path (兼容性好)
current_dir = os.path.dirname(os.path.abspath(__file__))
return current_dir
def get_parent_directory():
"""獲取父目錄"""
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
return parent_dir
def get_subdirectory(subdir_name):
"""構建子目錄路徑"""
current_dir = os.path.dirname(os.path.abspath(__file__))
subdir = os.path.join(current_dir, subdir_name)
return subdir
# 使用示例
print("目錄操作示例:")
print(f"當前目錄: {get_current_directory()}")
print(f"父目錄: {get_parent_directory()}")
print(f"子目錄 'data': {get_subdirectory('data')}")
# 檢查目錄是否存在并創(chuàng)建
def ensure_directory_exists(dir_path):
"""確保目錄存在,不存在則創(chuàng)建"""
if not os.path.exists(dir_path):
os.makedirs(dir_path)
print(f"創(chuàng)建目錄: {dir_path}")
return dir_path
# 創(chuàng)建數(shù)據目錄
data_dir = ensure_directory_exists(get_subdirectory("data"))
print(f"數(shù)據目錄: {data_dir}")5. 在模塊中獲取模塊文件目錄
import os
import sys
def get_module_directory():
"""獲取調用者模塊的目錄"""
# 獲取調用棧信息
import inspect
frame = inspect.currentframe()
try:
# 獲取調用者所在的文件
caller_frame = frame.f_back
caller_file = caller_frame.f_globals.get('__file__')
if caller_file:
return os.path.dirname(os.path.abspath(caller_file))
else:
# 如果是交互式環(huán)境或編譯的模塊
return os.getcwd()
finally:
del frame # 避免循環(huán)引用
# 測試函數(shù)
def test_module_dir():
print(f"模塊目錄: {get_module_directory()}")
# 運行測試
test_module_dir()6. 處理特殊場景
import os
import sys
from pathlib import Path
def get_script_directory():
"""獲取腳本目錄,處理各種特殊情況"""
try:
# 方法1: 使用 __file__
if hasattr(sys, 'frozen'):
# 如果是打包后的exe文件
return os.path.dirname(sys.executable)
elif '__file__' in globals():
# 正常Python腳本
return os.path.dirname(os.path.abspath(__file__))
else:
# 交互式環(huán)境或其他情況
return os.getcwd()
except Exception as e:
print(f"獲取目錄出錯: {e}")
return os.getcwd()
def get_all_directories():
"""獲取所有相關目錄信息"""
directories = {}
# 當前文件目錄
if '__file__' in globals():
directories['文件目錄'] = os.path.dirname(os.path.abspath(__file__))
# 當前工作目錄
directories['工作目錄'] = os.getcwd()
# Python執(zhí)行文件目錄
directories['Python目錄'] = os.path.dirname(sys.executable)
# 用戶主目錄
directories['用戶主目錄'] = os.path.expanduser('~')
# 臨時目錄
directories['臨時目錄'] = os.path.join(os.path.expanduser('~'), 'tmp')
return directories
# 打印所有目錄信息
print("所有相關目錄:")
for name, path in get_all_directories().items():
print(f"{name:10}: {path}")
# 處理符號鏈接
def get_real_directory():
"""獲取真實目錄(解析符號鏈接)"""
if '__file__' in globals():
real_path = os.path.realpath(__file__)
return os.path.dirname(real_path)
return os.getcwd()
print(f"\n真實目錄(解析符號鏈接): {get_real_directory()}")7. 構建路徑的實用函數(shù)
import os
from pathlib import Path
class PathManager:
"""路徑管理器"""
def __init__(self, base_path=None):
"""初始化路徑管理器"""
if base_path is None:
self.base_path = self.get_current_file_directory()
else:
self.base_path = base_path
@staticmethod
def get_current_file_directory():
"""獲取當前文件目錄"""
return os.path.dirname(os.path.abspath(__file__))
def get_absolute_path(self, relative_path):
"""獲取基于基礎目錄的絕對路徑"""
return os.path.join(self.base_path, relative_path)
def get_path_object(self, relative_path):
"""獲取Path對象"""
return Path(self.base_path) / relative_path
def ensure_directory(self, relative_path):
"""確保目錄存在"""
dir_path = self.get到此這篇關于Python獲取當前文件目錄的多種方法的文章就介紹到這了,更多相關Python獲取當前文件目錄內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
探索Python fcntl模塊文件鎖和文件控制的強大工具使用實例
這篇文章主要介紹了Python fcntl模塊文件鎖和文件控制的強大工具使用實例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Python學習筆記之函數(shù)的參數(shù)和返回值的使用
這篇文章主要介紹了Python學習筆記之函數(shù)的參數(shù)和返回值的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Python Pandas實現(xiàn)數(shù)據分組求平均值并填充nan的示例
今天小編就為大家分享一篇Python Pandas實現(xiàn)數(shù)據分組求平均值并填充nan的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python超詳細實現(xiàn)完整學生成績管理系統(tǒng)
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實現(xiàn)一個完整版學生成績管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-03-03

