如何在Python中获取含驱动器和计算机名的Documents文件夹路径?
优雅获取Windows用户Documents路径的驱动器名与用户名(computer_name)
别再拆字符串了,直接调用系统API获取标准路径才是靠谱方案,不同语言的实现如下:
Python
直接利用系统内置的路径获取方法,避免手动拼接和字符串拆分:
from pathlib import Path # 获取用户主目录(即C:\Users\<computer_name>) home_dir = Path.home() # 构造Documents路径 documents_dir = home_dir / "Documents" # 提取驱动器名(如C:) drive_name = home_dir.drive # 提取用户名(即你说的computer_name) computer_name = home_dir.name
如果要直接获取Documents的完整路径,也可以用win32com调用Windows Shell的特殊文件夹接口:
import win32com.client from pathlib import Path shell = win32com.client.Dispatch("WScript.Shell") documents_path = Path(shell.SpecialFolders("MyDocuments")) drive_name = documents_path.drive # Documents的父目录就是用户文件夹,直接取名称 computer_name = documents_path.parent.name
C#
用Environment类获取系统特殊文件夹路径,再提取所需信息:
using System; using System.IO; string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 提取驱动器名(如C:\) string driveName = Path.GetPathRoot(documentsPath); // 获取用户主目录,再提取用户名 string userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string computerName = Path.GetFileName(userProfilePath);
PowerShell
通过.NET类直接获取,简洁高效:
# 获取Documents文件夹路径 $documentsPath = [Environment]::GetFolderPath('MyDocuments') # 提取驱动器名 $driveName = Split-Path -Path $documentsPath -Qualifier # 向上两级取用户名(Documents的父目录是用户文件夹) $computerName = Split-Path -Path (Split-Path -Path $documentsPath -Parent) -Leaf
为什么不要拆分当前工作目录?
当前工作目录完全可能不在用户目录范围内(比如程序被放到D盘运行),这种情况下拆分出来的驱动器名和用户名全是错的。调用系统API获取特殊文件夹路径是Windows官方推荐的方式,能适配不同系统配置(比如用户把Documents移到其他驱动器的情况),可靠性拉满。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

