Python 如何获取桌面位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34275782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Desktop location?
提问by Ben L
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.
我在 Windows 上使用 Python,我希望我的脚本的一部分将文件从某个目录(我知道它的路径)复制到桌面。
I used this:
我用过这个:
shutil.copy(txtName, '%HOMEPATH%/desktop')
While txtName
is the txt File's name (with full path).
而txtName
txt 文件的名称(带完整路径)。
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.
我希望脚本可以在任何计算机上运行。
采纳答案by tpearse
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.
您可以使用os.environ["HOMEPATH"]
来获取路径。现在,它实际上是在尝试查找%HOMEPATH%/Desktop
而不替换实际路径。
Maybe something like:
也许是这样的:
shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))
回答by tpearse
On Unix or Linux:
在 Unix 或 Linux 上:
import os
desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
on Windows:
在 Windows 上:
import os
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
and to add in your command:
并添加您的命令:
shutil.copy(txtName, desktop)
回答by GPCracker
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
我还不能发表评论,但基于将位置连接到用户路径与“桌面”的解决方案具有有限的设备,因为桌面可以并且经常被重新映射到非系统驱动器。要获得真实位置,应使用 Windows 注册表...或通过 ctypes 等特殊功能,如https://stackoverflow.com/a/626927/7273599
回答by dashesy
This works on both Windows and Linux:
这适用于 Windows 和 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"))
回答by dashesy
Try this:
尝试这个:
import os
file1 =os.environ["HOMEPATH"] + "\Desktop\myfile.txt"
回答by Salamandar
All those answers are intrinsecally wrong : they only work for english sessions.
所有这些答案本质上都是错误的:它们仅适用于英语会话。
You should check the XDG directories instead of supposing it's always 'Desktop'
.
您应该检查 XDG 目录,而不是假设它总是'Desktop'
.
Here's the correct answer: How to get users desktop path in python independent of language install (linux)
这是正确的答案:How to get users desktop path in python independent language install (linux)
回答by johnson
For 3.5+ you can use pathlib:
对于 3.5+,您可以使用 pathlib:
import pathlib
desktop = pathlib.Path.home() / 'Desktop'