我想编写一个进入桌面文件夹的程序,并执行诸如创建文件夹之类的命令。我有这个:
import os
def run_command(command):
os.system(f'cmd /c "{command}"')
"""
This command is running in the folder of this Python file, thus I can only access folders from this directory.
But I want it to go to the Desktop folder and make a new directory there.
"""
run_command("cd Desktop") # It makes an error "The system cannot find the path specified."
run_command("md Folder")
r"""I want the directory to be C:\Users\<username>"""
正如您在注释中看到的那样,它在您运行此 Python 文件的目录中执行所有操作。但我希望目录为“C:\Users<username>”。如果您手动打开 cmd 提示,这就是您得到的结果。如何使其目录为“C:\Users<username>”?或者如果有更好的方法,我该怎么做?
谢谢你的帮助。
使用os.chdir
更改Python是“运行”的目录。
os.chdir('C:\Users\someuser')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句