Python 2.7 WindowsError:[错误3]系统找不到指定的路径:';C:\\Documents and Settings\\%username%\\Desktop';

Python 2.7 WindowsError:[错误3]系统找不到指定的路径:';C:\\Documents and Settings\\%username%\\Desktop';,python-2.7,path,Python 2.7,Path,我想在脚本执行期间将当前工作目录更改为桌面 我用过: import os os.chdir("C:\Documents and Settings\%username%\Desktop") 但它显示的是错误3 WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Documents and Settings\\%username%\\Desktop' 从,看起来您需要这个(我在mac上,所以我自己无法测

我想在脚本执行期间将当前工作目录更改为桌面

我用过:

import os

os.chdir("C:\Documents and Settings\%username%\Desktop")
但它显示的是错误3

WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Documents and Settings\\%username%\\Desktop'
从,看起来您需要这个(我在mac上,所以我自己无法测试):


我建议这样做:

import os

os.chdir(os.path.expandvars("C:\Documents and Settings\${username}\Desktop"))

此解决方案更通用,因为它适用于任何环境变量。

因为没有名为%username%的用户,我希望此代码在多台计算机上工作。我无法在脚本中硬编码我的用户名。。有什么方法可以概括这一点吗。上面的代码在cmd中工作,所以我认为它也可能在python中工作。
%username%
是一个环境变量。您必须在路径名中展开它。
import os

os.chdir(os.path.expandvars("C:\Documents and Settings\${username}\Desktop"))