How to get Desktop location?

2019-02-07 01:21发布

I'm using Python on Windows and I want a part of my script to copy a file from a certain directory (I know its path) to the Desktop.

I used this:

shutil.copy(txtName, '%HOMEPATH%/desktop')

While txtName is the txt File's name (with full path).

I get the error:

IOError: [Errno 2] No such file or directory: '%HOMEPATH%/DESKTOP'

Any help?

I want the script to work on any computer.

4条回答
\"骚年 ilove
2楼-- · 2019-02-07 01:52

I can not comment yet, but solutions based on joining location to a user path with 'Desktop' have limited appliance because Desktop could and often is being remapped to a non-system drive. To get real location a windows registry should be used... or special functions via ctypes like https://stackoverflow.com/a/626927/7273599

查看更多
戒情不戒烟
3楼-- · 2019-02-07 02:01

This works on both Windows and Linux:

import os
desktop = os.path.expanduser("~/Desktop")

# the above is valid on Windows (after 7) but if you want it in os normalized form:
desktop = os.path.normpath(os.path.expanduser("~/Desktop"))
查看更多
Ridiculous、
4楼-- · 2019-02-07 02:04

On Unix or Linux:

import os
desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') 

on Windows:

import os
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') 

and to add in your command:

shutil.copy(txtName, desktop)
查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-07 02:05

You can use os.environ["HOMEPATH"] to get the path. Right now it's literally trying to find %HOMEPATH%/Desktop without substituting the actual path.

Maybe something like:

shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))
查看更多
登录 后发表回答