python
主页 > 脚本 > python >

Python获取Windows桌面路径的三种方法

2024-12-02 | 佚名 | 点击:

1 概述

2 方法

2.1 方法1:使用 os 模块

1

2

3

4

5

6

7

8

9

10

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 模块

1

2

3

4

5

6

7

8

9

10

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 模块

1

2

3

4

5

6

7

8

9

from pathlib import Path

 

 

def get_desktop_path():

    return Path.home() / 'Desktop'

 

 

print(get_desktop_path())

# C:\Users\Administrator\Desktop

 

原文链接:
相关文章
最新更新