Python 获取当前路径几种方法

本文详细介绍了使用Python获取当前路径的三种方法:通过os.path.dirname结合os.path.abspath获取绝对路径,利用os.getcwd获取当前工作目录,并展示了如何适配不同操作系统路径格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 获取当前路径的几种方法


绝对路径

1、os.path 方法

# -*- coding: utf-8 -*-
# !/usr/bin/python

import os
import sys

current_directory = os.path.dirname(os.path.abspath(__file__))

print(current_directory)


输出:
Alt

2、os.path.abspath 方法

# -*- coding: utf-8 -*-
# !/usr/bin/python

import os
import sys

root_path = os.path.abspath(os.path.dirname(current_directory) + os.path.sep + ".")
sys.path.append(root_path)

print(sys.path[0])

输出:
Alt

3、os.getcwd 方法

currentPath = os.getcwd().replace('\\','/')    # 获取当前路径

print(currentPath)

输出:
Alt


### Python获取当前文件路径方法Python 编程中,`os` 和 `os.path` 模块提供了多种方法用于获取当前文件的路径。以下是几种常见的实现方式及其适用场景。 #### 方法一:使用 `os.path.abspath(__file__)` 此方法可以返回当前脚本文件的绝对路径。它利用了特殊变量 `__file__`,该变量存储着当前执行脚本的文件名或相对路径[^1]。 ```python import os script_path = os.path.abspath(__file__) print(f"Current script absolute path: {script_path}") ``` #### 方法二:结合 `os.getcwd()` 使用 如果需要获取当前的工作目录而非具体脚本位置,则可采用 `os.getcwd()` 函数。需要注意的是,工作目录可能与脚本所在的目录不同[^2]。 ```python current_working_directory = os.getcwd() print(f"Current working directory: {current_working_directory}") ``` #### 方法三:提取脚本所在目录 当仅需知道脚本所属的目录而不关心确切文件名称时,可以通过组合 `os.path.dirname()` 和 `os.path.abspath(__file__)` 来完成这一需求[^3]。 ```python dir_path = os.path.dirname(os.path.abspath(__file__)) print(f"Script's directory: {dir_path}") ``` #### 方法四:更全面的信息——分解路径组件 对于某些复杂情况,比如既想得到完整的父级目录又想知道基础文件名字串,那么调用 `os.path.split()` 是非常合适的解决方案之一[^5]。 ```python split_result = os.path.split(os.path.abspath(__file__)) parent_dir, base_name = split_result print(f"Parent Directory: {parent_dir}, Base Name: {base_name}") ``` 以上四种途径各有侧重,在实际应用过程中可以根据项目特点灵活选用最适合的一种或者混合搭配起来满足特定业务逻辑的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大小宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值