如何获取桌面位置?

人气:227 发布:2022-10-16 标签: desktop python filepath copy

问题描述

我在 Windows 上使用 Python,我希望脚本的一部分将文件从某个目录(我知道它的路径)复制到桌面.

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.

我用过这个:

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

txtName 是 txt 文件的名称(带有完整路径).

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

我得到错误:

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

有什么帮助吗?

我希望脚本可以在任何计算机上运行.

I want the script to work on any computer.

推荐答案

你可以使用os.environ["HOMEPATH"]来获取路径.现在它实际上是在尝试查找 %HOMEPATH%/Desktop 而不替换实际路径.

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.

可能是这样的:

shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))

286