Python OS更换路径

发布于 2025-02-10 04:42:53 字数 541 浏览 2 评论 0原文

在调用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

司马昭之心 2025-02-17 04:42:53

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. Try os.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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文