Python獲取Windows桌面路徑的三種方法
更新時間:2024年12月01日 09:49:28 作者:魚丸丶粗面
在日常編程工作中,有時我們需要將文件或數(shù)據(jù)自動保存到用戶的桌面上以便于快速訪問,在 Windows 操作系統(tǒng)中,可以通過多種方式來獲取桌面路徑,本文將詳細介紹三種常用的方法,需要的朋友可以參考下
1 概述
- 因為某些原因,需要使用不同用戶的 Windows 桌面路徑,故無法對路徑進行固定,可使用下列方法進行獲取
# 參考:Administrator 賬號的桌面地址 C:\Users\Administrator\Desktop
2 方法
2.1 方法1:使用 os 模塊
import os
def get_desktop_path():
return os.path.join(os.path.expanduser("~"), 'Desktop')
desktop_path = get_desktop_path()
print(desktop_path)
# C:\Users\Administrator\Desktop
2.2 方法2:使用 winreg 模塊
import winreg
def get_desktop():
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
return winreg.QueryValueEx(key, "Desktop")[0]
print(get_desktop())
# C:\Users\Administrator\Desktop
2.3 方法3:使用 path 模塊
from pathlib import Path
def get_desktop_path():
return Path.home() / 'Desktop'
print(get_desktop_path())
# C:\Users\Administrator\Desktop
到此這篇關于Python獲取Windows桌面路徑的三種方法的文章就介紹到這了,更多相關Python獲取Windows桌面路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python面向對象實現(xiàn)名片管理系統(tǒng)文件版
這篇文章主要為大家詳細介紹了python面向對象實現(xiàn)名片管理系統(tǒng)文件版,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04

