Python如何判断文件是否位于macOS系统的Desktop桌面文件夹中
macOS Big Sur 下Python获取桌面路径及判断文件归属方案
核心说明
os.getcwd()返回的是脚本进程当前的工作目录,会随脚本执行位置变化,不适合用来拼接固定的桌面路径。以下方案可稳定获取当前用户的桌面路径:
方案1:使用os模块(兼容所有Python版本)
import os # 直接获取桌面绝对路径,macOS下默认格式为/Users/用户名/Desktop desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") # 判断目标文件是否位于桌面内 target_file = "你要判断的文件路径" # 先转成绝对路径再判断公共前缀 abs_target = os.path.abspath(target_file) is_in_desktop = os.path.commonprefix([abs_target, desktop_path]) == desktop_path
方案2:使用pathlib(Python3.4+推荐,语法更简洁)
from pathlib import Path # 获取桌面路径 desktop_path = Path.home() / "Desktop" # 判断目标文件是否位于桌面内 target_file = Path("你要判断的文件路径").resolve() is_in_desktop = target_file.is_relative_to(desktop_path)
适配自定义桌面路径的特殊场景
如果你手动修改过桌面的默认存储位置,可以通过读取macOS系统配置获取真实桌面路径:
import os import subprocess try: # 读取Finder的桌面路径配置 custom_desktop = subprocess.check_output( ["defaults", "read", "com.apple.finder", "DesktopPath"], text=True ).strip() # 处理~开头的相对路径 if custom_desktop.startswith("~"): custom_desktop = os.path.expanduser(custom_desktop) # 路径存在就用自定义值,不存在回退到默认路径 desktop_path = custom_desktop if os.path.exists(custom_desktop) else os.path.join(os.path.expanduser("~"), "Desktop") except subprocess.CalledProcessError: # 读取配置失败时使用默认路径 desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
内容的提问来源于stack exchange,提问作者Nomore
相关产品推荐
相关产品推荐

