将目录更改为";C:\Users\<;用户名>&引用;使用Python操作系统

将目录更改为";C:\Users\<;用户名>&引用;使用Python操作系统,python,cmd,operating-system,Python,Cmd,Operating System,我想写一个程序,去桌面文件夹,并做命令,如使一个文件夹。我有这个: 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.

我想写一个程序,去桌面文件夹,并做命令,如使一个文件夹。我有这个:

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>"""
导入操作系统
def run_命令(命令):
操作系统(f'cmd/c“{command}”)
"""
这个命令正在这个Python文件的文件夹中运行,因此我只能从这个目录访问文件夹。
但我希望它转到桌面文件夹,并在那里创建一个新目录。
"""
运行_命令(“cd桌面”)#它会出错“系统找不到指定的路径”
运行命令(“md文件夹”)
r“”“我希望目录为C:\Users\”
正如您在注释中所看到的,它在您运行此Python文件的目录中执行所有操作。但我希望目录是“C:\Users”。这是手动打开命令提示符时得到的结果。如何将其目录设置为“C:\Users”?或者如果有更好的方法,我该怎么做


感谢您的帮助。

使用
os.chdir
更改Python正在“运行”的目录


使用
os.chdir
更改Python正在“运行”的目录


正如James所说,
os.chdir
应该可以工作。但是您应该记住,字符
\
是转义字符,为了使用它,字符串的前缀必须是r:
r“C:\Users\user”
,或者必须转义为:
“C:\\Users\\user”

获取当前用户的另一个简单方法是使用内置的
getpass
模块

导入getpass
打印(getpass.getuser())

正如詹姆斯所说,
os.chdir
应该可以工作。但是您应该记住,字符
\
是转义字符,为了使用它,字符串的前缀必须是r:
r“C:\Users\user”
,或者必须转义为:
“C:\\Users\\user”

获取当前用户的另一个简单方法是使用内置的
getpass
模块

导入getpass
打印(getpass.getuser())

此代码利用环境变量获取正确的桌面目录并调用正确的命令处理器

它还使用
os.path.join
创建目录路径。由于
Desktop
是硬编码的,因此反向索利多金币(反斜杠)也可能是硬编码的。但是,使用
os.path.join
的实践将使代码可移植到运行Python的所有系统中

import os

def run_command(command):
    os.chdir(os.path.join(os.environ['USERPROFILE'], 'Desktop'))
    os.system(os.environ['ComSpec'] + ' /c "cd"')

此代码使用环境变量获取正确的桌面目录并调用正确的命令处理器

它还使用
os.path.join
创建目录路径。由于
Desktop
是硬编码的,因此反向索利多金币(反斜杠)也可能是硬编码的。但是,使用
os.path.join
的实践将使代码可移植到运行Python的所有系统中

import os

def run_command(command):
    os.chdir(os.path.join(os.environ['USERPROFILE'], 'Desktop'))
    os.system(os.environ['ComSpec'] + ' /c "cd"')