Python獲取當(dāng)前文件目錄的多種方法
概述
在 Python 中獲取當(dāng)前文件目錄有多種方法,下面詳細(xì)介紹各種方式及其適用場景。
1. 基礎(chǔ)方法
import os
# 1. 獲取當(dāng)前文件的絕對路徑
current_file_path = os.path.abspath(__file__)
print(f"當(dāng)前文件的絕對路徑: {current_file_path}")
# 2. 獲取當(dāng)前文件所在目錄
current_dir = os.path.dirname(current_file_path)
print(f"當(dāng)前文件所在目錄: {current_dir}")
# 3. 直接獲取目錄(常用寫法)
current_directory = os.path.dirname(os.path.abspath(__file__))
print(f"當(dāng)前目錄(常用寫法): {current_directory}")
# 4. 獲取當(dāng)前工作目錄(可能不是文件所在目錄)
working_directory = os.getcwd()
print(f"當(dāng)前工作目錄: {working_directory}")2. 使用__file__屬性
import os
# 1. 在不同環(huán)境下的表現(xiàn)
print(f"__file__ 屬性值: {__file__}")
# 2. 處理相對路徑
if not os.path.isabs(__file__):
# 如果是相對路徑,轉(zhuǎn)換為絕對路徑
abs_path = os.path.abspath(__file__)
print(f"轉(zhuǎn)換為絕對路徑: {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. 獲取當(dāng)前文件路徑
current_file = Path(__file__).resolve() # 解析為絕對路徑
print(f"Path對象: {current_file}")
print(f"當(dāng)前文件路徑: {str(current_file)}")
# 2. 獲取當(dāng)前文件所在目錄
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目錄詳細(xì)信息:")
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. 不同場景下的應(yīng)用
import os
import sys
from pathlib import Path
def get_current_directory():
"""獲取當(dāng)前文件目錄的函數(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):
"""構(gòu)建子目錄路徑"""
current_dir = os.path.dirname(os.path.abspath(__file__))
subdir = os.path.join(current_dir, subdir_name)
return subdir
# 使用示例
print("目錄操作示例:")
print(f"當(dāng)前目錄: {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ù)據(jù)目錄
data_dir = ensure_directory_exists(get_subdirectory("data"))
print(f"數(shù)據(jù)目錄: {data_dir}")5. 在模塊中獲取模塊文件目錄
import os
import sys
def get_module_directory():
"""獲取調(diào)用者模塊的目錄"""
# 獲取調(diào)用棧信息
import inspect
frame = inspect.currentframe()
try:
# 獲取調(diào)用者所在的文件
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():
"""獲取所有相關(guān)目錄信息"""
directories = {}
# 當(dāng)前文件目錄
if '__file__' in globals():
directories['文件目錄'] = os.path.dirname(os.path.abspath(__file__))
# 當(dāng)前工作目錄
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("所有相關(guān)目錄:")
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. 構(gòu)建路徑的實用函數(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():
"""獲取當(dāng)前文件目錄"""
return os.path.dirname(os.path.abspath(__file__))
def get_absolute_path(self, relative_path):
"""獲取基于基礎(chǔ)目錄的絕對路徑"""
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到此這篇關(guān)于Python獲取當(dāng)前文件目錄的多種方法的文章就介紹到這了,更多相關(guān)Python獲取當(dāng)前文件目錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python連接MySQL報錯:缺少cryptography庫的解決辦法
這篇文章主要介紹了Python連接MySQL報錯:缺少cryptography庫的兩種解決辦法,分別是安裝cryptography庫和修改MySQL用戶認(rèn)證方式,兩種方法各有適用場景,需要的朋友可以參考下2026-06-06
詳解Python中Pandas read_csv參數(shù)使用
在使用 Pandas 進(jìn)行數(shù)據(jù)分析和處理時,read_csv 是一個非常常用的函數(shù),本文將詳細(xì)介紹 read_csv 函數(shù)的各個參數(shù)及其用法,希望對大家有所幫助2022-10-10
Python進(jìn)行數(shù)據(jù)可視化Plotly與Dash的應(yīng)用小結(jié)
數(shù)據(jù)可視化是數(shù)據(jù)分析中至關(guān)重要的一環(huán),它能夠幫助我們更直觀地理解數(shù)據(jù)并發(fā)現(xiàn)隱藏的模式和趨勢,本文主要介紹了Python進(jìn)行數(shù)據(jù)可視化Plotly與Dash的應(yīng)用小結(jié),具有一定的參考價值,感興趣的可以了解一下2024-04-04
詳解Python中sorted()和sort()的使用與區(qū)別
眾所周知,在Python中常用的排序函數(shù)為sorted()和sort()。本文將詳細(xì)介紹sorted()和sort()方法的代碼示例,并解釋兩者之間的區(qū)別,感興趣的可以了解一下2022-03-03
win8下python3.4安裝和環(huán)境配置圖文教程
這篇文章主要為大家詳細(xì)介紹了win8下python3.4安裝和環(huán)境配置圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07

