Python OS更换路径
在调用CMD中的Python文件时,我正在尝试更改目录,但它不起作用! 我尝试了所有类型的斜线&后斜线&逃脱,有时在代码运行时,目录不会更改,并且在启动PY文件的地方保持不变,有时代码不运行,我有此错误错误
import os
#import sys
os.chdir('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data')
os.system('cd \"%SystemRoot%\\Users\\%username%\\AppData\\Local\\Google\\Chrome\\User Data\"')
我试图更改系统变量%system root%和%username%tos c:/and user2(我的系统根和用户名),但仍然不工作! 谁能在他的计算机上尝试并告诉我该更改PLS? 谢谢 !
I'm trying to change directory when calling a python file in cmd but it's not working !
I tried all types of slashes & back slashes & escaping, sometimes when the code runs, the directory isn't changing and stays the same where i start the py file and sometimes the code isn't running and i have this error Error
import os
#import sys
os.chdir('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data')
os.system('cd \"%SystemRoot%\\Users\\%username%\\AppData\\Local\\Google\\Chrome\\User Data\"')
I tried to change the system variables %SystemRoot% and %username% to words like C:/ and user2 (my system root and user name ) but still not working !
Can anyone try it in his computer and tell me what to change pls ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python不会自动扩展shell变量,例如
%systemRoot%
和%用户名
的实际值,这就是导致您遇到的错误的原因。尝试OS.CHDIR(OS.PATH..EXPANDVARS(OS.PATH.Expanduser)('%SystemRoot%/users/%用户名%/appdata/local/local/google/google/chrome/user data'))
for第一行应该将%用户名%
和%SystemRoot%
变量扩展到有效的路径。编辑:对不起,我误解了您的问题。虽然这将照顾您遇到的错误,但您不能从脚本中更改外壳的工作目录;请参阅您的问题下的评论,作者:
Python does not automatically expand shell variables like
%SystemRoot%
and%username%
to their actual values, this is what caused the error you were getting. Tryos.chdir(os.path.expandvars(os.path.expanduser('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data')))
for the first line as this should expand the%username%
and%SystemRoot%
variables to a valid path.EDIT: Sorry, I misunderstood your question. While this will take care of the error you were getting, you cannot change the shell's working directory from your script; see comment under your question by Ulrich Eckhardt