python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python获取当前文件目录

Python获取当前文件目录的多种方法

作者:mftang

文章介绍了在Python中获取当前文件目录的多种方法,包括基础方法、使用__file__属性、使用pathlib模块(推荐于Python3.4+),并在不同场景下应用这些方法,此外,还讨论了如何在模块中获取文件目录、处理特殊场景以及构建路径的实用函数,需要的朋友可以参考下

概述

在 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. 在不同环境下的表现
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():
    """获取当前文件目录的函数"""
    # 方法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')}")

# 检查目录是否存在并创建
def ensure_directory_exists(dir_path):
    """确保目录存在,不存在则创建"""
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
        print(f"创建目录: {dir_path}")
    return dir_path

# 创建数据目录
data_dir = ensure_directory_exists(get_subdirectory("data"))
print(f"数据目录: {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:
            # 如果是交互式环境或编译的模块
            return os.getcwd()
    finally:
        del frame  # 避免循环引用

# 测试函数
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:
            # 交互式环境或其他情况
            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执行文件目录
    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. 构建路径的实用函数

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获取当前文件目录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文