【问题标题】:Change the directory to "C:\Users\<username>" with Python OS使用 Python 操作系统将目录更改为“C:\Users\<username>”
【发布时间】:2021-03-27 20:46:36
【问题描述】:

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

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>"""

正如您在 cmets 中看到的,它执行您运行此 Python 文件的目录中的所有操作。但我希望目录为“C:\Users”。如果您手动打开 cmd 提示符,这就是您所得到的。如何使其目录为“C:\Users”?或者如果有更好的方法,我该怎么做?

感谢您的帮助。

【问题讨论】:

    标签: python cmd operating-system


    【解决方案1】:

    就像詹姆斯说的那样,os.chdir 应该可以工作。但是你应该记住字符\是一个转义字符,为了使用它,字符串必须以r为前缀:r"C:\Users\user"或者必须转义:"C:\\Users\\user"

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

    import getpass
    print(getpass.getuser())
    

    【讨论】:

      【解决方案2】:

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

      os.chdir('C:\Users\someuser')
      

      【讨论】:

        【解决方案3】:

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

        它还使用os.path.join 来创建目录路径。由于 Desktop 是硬编码的,因此 REVERSE SOLIDUS(反斜杠)也可能是硬编码的。但是,练习使用 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"')
        

        【讨论】:

          猜你喜欢
          • 2011-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-03
          • 1970-01-01
          • 1970-01-01
          • 2017-02-11
          • 1970-01-01
          相关资源
          最近更新 更多