AIGC标识 跨平台获取桌面路径

跨平台获取桌面路径

from pathlib import Path
import os
import json

def get_desktop_path():
    # Windows/Macos
    if os.name == "nt":
        return Path.home() / "Desktop"

    # linux
    xdg_config = Path.home() / ".config" / "user-dirs.dirs"
    """这里为啥是(/)来拼接路径,
        class Path:
            def __truediv__(self, other):
                return self._make_child((other, ))
        __truediv__就是/背后调用的函数。
        所以 Path.home() / "Desktop"
        实际 Path.home().__truediv__("Desktop")
        内部干的事就是等价于"拼路径 + 规范化",返回一个新的Path对象。
    """
    if xdg_config.exists():
        for line in xdg_config.read_text(encoding="utf-8").splitlines():
            if line.startswith("XDG_DESKTOP_DIR"):
                #path = line.split('=')[1].strip().strip('"')
                path=line.split("=", 1)[1].strip().strip('"')
                path = path.replace("$HOME", str(Path.home()))
                return Path(path)
        return Path.home()/"Desktop"

desktop = get_desktop_path()
print(desktop)
posted @ 2026-11-16 02:20  还在printf  阅读(9)  评论(0)    收藏  举报