Python常见目录的获取及路径拼接

获取目录

工作目录

os.getcwd() 获取的是当前工作目录(Current Working Directory,CWD)。

假设你有一个脚本 my_script.py 放在 /home/user/scripts 目录下.

你可以在不同的目录中运行这个脚本,比如从 /home/user 目录或者 /home/user/projects 目录运行:

1
2
3
4
5
6
7
# 从 /home/user 目录运行脚本
cd /home/user
python scripts/my_script.py

# 从 /home/user/projects 目录运行脚本
cd /home/user/projects
python ../scripts/my_script.py

在这两种情况下,my_script.py 中的 os.getcwd() 将返回不同的路径:

  • 在第一种情况下,os.getcwd() 将返回 /home/user
  • 在第二种情况下,os.getcwd() 将返回 /home/user/projects

当前脚本所在目录

1
2
3
4
5
6
7
8
9
import os

# 获取当前脚本的绝对路径
script_path = os.path.abspath(__file__)

# 获取当前脚本所在的目录
script_directory = os.path.dirname(script_path)

print("脚本所在目录:", script_directory)

上级目录

要获取当前脚本所在目录的上级目录,可以在获取当前脚本目录后,再使用路径操作函数来获取上级目录。以下是几种常见的方法:

方法 1: 使用 os 模块

1
2
3
4
5
6
7
8
9
10
11
12
import os

# 获取当前脚本的绝对路径
script_path = os.path.abspath(__file__)

# 获取当前脚本所在的目录
script_directory = os.path.dirname(script_path)

# 获取上级目录
parent_directory = os.path.dirname(script_directory)

print("脚本所在目录的上级目录:", parent_directory)

方法 2: 使用 pathlib 模块

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

# 获取当前脚本的路径
script_path = Path(__file__).resolve()

# 获取当前脚本所在的目录
script_directory = script_path.parent

# 获取上级目录
parent_directory = script_directory.parent

print("脚本所在目录的上级目录:", parent_directory)

注意script_path.parentpathlib.Path 对象,而不是普通的字符串。

如果你想将 Path 对象与其他字符串拼接,需要先将 Path 对象转换为字符串。

你可以使用 str() 函数来进行转换。

1
2
script_path = Path(__file__).resolve()
project_path = str(script_path.parent.parent)

路径拼接

路径拼接不要自己用斜杠拼接,在不同的系统上会有兼容性问题。

os.path

1
2
3
script_path = Path(__file__).resolve()
project_path = str(script_path.parent.parent)
model_filepath = os.path.join(project_path, "ml-resource","knn_model.xml")

pathlib

pathlib 提供了更简洁的方式来拼接多个路径段,使用 / 运算符:

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

# 拼接多个路径
base_dir = Path('/path/to/directory')
sub_dir = 'subdirectory'
file_name = 'file.txt'

full_path = base_dir / sub_dir / file_name
print(full_path)

这里的full_path是对象

1
full_path_str = str(full_path)

创建文件夹

1
2
3
output_directory = r"D:\test"
if not os.path.exists(output_directory):
os.makedirs(output_directory)

常见的系统目录

在 Python 中,你可以使用 os 模块和 pathlib 模块来获取系统的常用目录。

这些模块提供了访问文件系统路径的便捷方法。

以下是一些常见的系统目录及其获取方法:

获取当前工作目录

1
2
3
4
import os

current_directory = os.getcwd()
print("当前工作目录:", current_directory)

获取用户的主目录

1
2
3
4
import os

home_directory = os.path.expanduser("~")
print("用户主目录:", home_directory)

获取临时目录

1
2
3
4
import tempfile

temp_directory = tempfile.gettempdir()
print("临时目录:", temp_directory)

获取系统的配置文件目录

在 Linux 和 macOS 上,配置文件通常存储在 ~/.config 目录下。在 Windows 上,配置文件通常存储在 C:\Users\<用户名>\AppData\Roaming 目录下。

1
2
3
4
5
6
7
8
9
import os
import platform

if platform.system() == "Windows":
config_directory = os.path.join(os.getenv("APPDATA"), "YourAppName")
else:
config_directory = os.path.join(os.path.expanduser("~"), ".config", "YourAppName")

print("配置文件目录:", config_directory)

获取系统的桌面目录

1
2
3
4
5
6
7
8
9
10
11
import os
import platform

if platform.system() == "Windows":
desktop_directory = os.path.join(os.getenv("USERPROFILE"), "Desktop")
elif platform.system() == "Darwin": # macOS
desktop_directory = os.path.join(os.path.expanduser("~"), "Desktop")
else: # Linux
desktop_directory = os.path.join(os.path.expanduser("~"), "Desktop")

print("桌面目录:", desktop_directory)

获取系统的文档目录

1
2
3
4
5
6
7
8
9
10
11
import os
import platform

if platform.system() == "Windows":
documents_directory = os.path.join(os.getenv("USERPROFILE"), "Documents")
elif platform.system() == "Darwin": # macOS
documents_directory = os.path.join(os.path.expanduser("~"), "Documents")
else: # Linux
documents_directory = os.path.join(os.path.expanduser("~"), "Documents")

print("文档目录:", documents_directory)

获取系统的下载目录

1
2
3
4
5
6
7
8
9
10
11
import os
import platform

if platform.system() == "Windows":
downloads_directory = os.path.join(os.getenv("USERPROFILE"), "Downloads")
elif platform.system() == "Darwin": # macOS
downloads_directory = os.path.join(os.path.expanduser("~"), "Downloads")
else: # Linux
downloads_directory = os.path.join(os.path.expanduser("~"), "Downloads")

print("下载目录:", downloads_directory)

获取系统的应用程序目录

在 macOS 上,应用程序通常存储在 /Applications 目录下。

在 Windows 上,应用程序通常存储在 C:\Program FilesC:\Program Files (x86) 目录下。

1
2
3
4
5
6
7
8
9
10
11
import os
import platform

if platform.system() == "Windows":
app_directory = os.getenv("ProgramFiles")
elif platform.system() == "Darwin": # macOS
app_directory = "/Applications"
else: # Linux
app_directory = "/usr/bin"

print("应用程序目录:", app_directory)

使用 pathlib 模块获取

pathlib 是 Python 3.4 引入的一个模块,提供了面向对象的路径操作方式。

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

# 获取用户主目录
home_directory = Path.home()
print("用户主目录:", home_directory)

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

# 获取临时目录
temp_directory = Path(tempfile.gettempdir())
print("临时目录:", temp_directory)

总结

通过 os 模块和 pathlib 模块,你可以方便地获取系统的常用目录。根据操作系统的不同,路径可能会有所不同,因此在编写跨平台代码时,建议使用 platform 模块来区分不同的操作系统。