Find the current directory and file's directory

Find the current directory and file’s directory

技术背景

在Python开发中,经常需要获取当前工作目录和当前文件所在的目录。这在处理文件读写、资源加载等操作时非常有用。Python提供了多种方法来实现这些功能,主要涉及os模块和pathlib模块。

实现步骤

使用os模块

获取当前文件所在目录的完整路径

1
2
import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

需要注意的是,如果已经使用os.chdir()改变了当前工作目录,上述代码可能无法正常工作,因为__file__常量的值是相对于当前工作目录的,且不受os.chdir()调用的影响。

获取当前工作目录

1
2
import os
cwd = os.getcwd()

获取当前目录的文件夹名称

1
2
3
4
5
import os
str1 = os.getcwd()
str2 = str1.split(os.sep)
n = len(str2)
print(str2[n - 1])

使用pathlib模块(Python 3.4及以上)

获取当前工作目录

1
2
from pathlib import Path
print(Path.cwd())

获取脚本文件的绝对路径

1
print(Path(__file__).resolve())

获取脚本所在目录的路径

1
print(Path(__file__).resolve().parent)

核心代码

os模块示例

1
2
3
4
5
6
7
8
9
import os

# 获取当前文件所在目录
dir_path = os.path.dirname(os.path.realpath(__file__))
print("当前文件所在目录:", dir_path)

# 获取当前工作目录
cwd = os.getcwd()
print("当前工作目录:", cwd)

pathlib模块示例

1
2
3
4
5
6
7
8
9
10
11
12
13
from pathlib import Path

# 获取当前工作目录
current_working_dir = Path.cwd()
print("当前工作目录:", current_working_dir)

# 获取脚本文件的绝对路径
script_absolute_path = Path(__file__).resolve()
print("脚本文件的绝对路径:", script_absolute_path)

# 获取脚本所在目录的路径
script_dir = Path(__file__).resolve().parent
print("脚本所在目录的路径:", script_dir)

最佳实践

  • 当需要兼容Python 3.4以下版本时,建议使用os模块。
  • 对于Python 3.4及以上版本,推荐使用pathlib模块,因为它提供了更面向对象的路径操作方式,代码更简洁易读。
  • 在处理文件路径时,尽量使用绝对路径,避免因工作目录的改变而导致的问题。

常见问题

__file__不可靠的情况

在某些情况下,如使用PyInstaller编译后,__file__可能无法正常工作,因为魔法属性在__main__级别未设置。此时可以考虑使用sys.argv[0]来获取当前文件的路径,但要注意它也会受到工作目录的影响。

Path对象在旧版本Python中的兼容性问题

在Python 3.4和3.5中,open内置函数只能处理字符串或字节对象,不支持Path对象。需要将Path对象转换为字符串或使用Path.open()方法。从Python 3.6开始,open函数支持PathLike对象,可以直接传递Path对象。例如:

1
2
3
4
5
6
7
8
9
10
11
from pathlib import Path

p = Path(__file__).resolve()

# Python 3.6及以上版本支持
with open(p) as f:
pass

# Python 3.4和3.5需要转换为字符串
with open(str(p)) as f:
pass

Find the current directory and file's directory
https://119291.xyz/posts/2025-05-12.find-the-current-directory-and-files-directory/
作者
ww
发布于
2025年5月12日
许可协议