使用 Python OS 将目录更改为“C:\Users\<username>”

Tkinter 情人

我想编写一个进入桌面文件夹的程序,并执行诸如创建文件夹之类的命令。我有这个:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用os.walk()递归遍历Python中的目录

python:将脚本工作目录更改为脚本自己的目录

无法使用os.Chdir()更改目录

如何在Rails的LOWER(“ users”。“ username”)上创建索引(使用postgres)

如何使用opencv python将黑色更改为红色

在Python中使用while函数将短语更改为向量

Python:使用os模块检查目录是否存在

使用os.expanduser(python)后查找文件目录

将Devise用户配置文件网址从.com / users / username更改为.com / username

如何使用colorama将Python背景更改为特定颜色?

Python os.chdir()到根目录实际上将目录更改为当前目录

在python中使用os更改目录

Powershell:获取Windows用户目录的大小(C:\ Users \ <UserName>)

如何使用os.walk()python计算目录的大小?

只想在Windows 7上使用PowerShell将目录从c:更改为e:

如何用C:\%USERPROFILE%批量替换C:\ Users \ username \ AppData

更改目录以写入新文件时,Python OS错误,必须使用chdir()

在Python中使用OS路径选择特定的目录路径

用以前的用户替换所有C:\ Users \ username \ *文件

如何使用Powershell将目录更改为程序文件?

使用python将所有html标记更改为符号

在for循环中使用os.chdir更改目录时出错-python

如何从 WSL 中获取 Windows 用户主目录 (/mnt/c/Users/username) 的路径?

使用 Python 将字符串变量更改为 JSON

使用“to_csv”和“os.path”将CSV保存在与python文件相同的目录中?

python代码需要获取用户的用户名才能打开C:/Users/USERNAME/目录下的文件

ENOENT:没有那个文件或目录,需要运行docker和nodejs时打开'C:\Users\username\package.json'

如何使用 Python 将背景颜色更改为图像的红色

如何使用 python 移动文件,在目标路径中使用 %username%