简体   繁体   English

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

[英]Python os.chdir() to root directory actually changes directory to current directory

I am working on a project on path D:/code/project . 我正在开发路径D:/code/project

project.py project.py

import os
import argparse

def create(path):
    if os.path.exists(path):
        os.chdir(path)
        app = open("app.py", "w+")
        app.write("print(\"Hello world!\")")
    else:
        path_list = path.split("/")
        for i in path_list:
            try:
                os.mkdir(i)
            except FileExistsError:
                pass
            except FileNotFoundError:
                print("Invalid path")
                exit()
            os.chdir(i)
        app = open("app.py", "w+")
        app.write("print(\"Hello world!\")")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    create_parser = parser.add_subparsers().add_parser("create")
    create_parser.add_argument("path", nargs="?", default=".", metavar="path", type=str)
    args = parser.parse_args()
    create(vars(args)["path"])

Basically, it has a custom command called create which takes path as an argument. 基本上,它具有一个名为create的自定义命令,该命令将path作为参数。 When it detects that path already exists, it will create a app.py at the directory specified, and if it does not, it will try and create the path and app.py . 当它检测到该path已经存在时,它将在指定的目录中创建一个app.py ,如果不存在,它将尝试创建该路径和app.py

However, when I run 但是,当我跑步时

D:/code/project> python project.py create D:/newpath

Instead of creating a new directory newpath under D: , it creates newpath under my current directory ( D:/code/project ). 而不是在D:下创建新目录newpath ,而是在当前目录( D:/code/project )下创建newpath

How do I change it such that changing directory to a root directory will actually switch correctly? 如何更改它,以便将目录更改为根目录实际上可以正确切换?

Your issue is with this line: 您的问题是与此行:

path_list = path.split("/")

On windows, that doesn't correctly split the path. 在Windows上,无法正确分割路径。 It leaves the drive letter 'D:' as a fragment all by itself, but when you try to change directory to that path, it does nothing (assuming the current directory was on D: somewhere). 它将驱动器号'D:'本身留为一个片段,但是当您尝试将目录更改为该路径时,它什么也不做(假设当前目录位于D:某处)。 It is the same behavior you get with the cd command on a command prompt. 与在命令提示符下使用cd命令得到的行为相同。 Drive letters in paths are pretty weird, they don't work like normal path prefixes. 路径中的驱动器字母很奇怪,它们不能像普通路径前缀一样工作。

To correctly split the path, use os.path.split(path) . 要正确分割路径,请使用os.path.split(path) It will correctly use 'D:/' as the first element of the path, which when you change to it will put you on the root folder of your drive. 它将正确使用'D:/'作为路径的第一个元素,当您更改为路径时,它将进入驱动器的根文件夹。

If you're using a recent version of Python (3.4+), you could also try using the pathlib module for a better, more object oriented way of manipulating paths: 如果您使用的是最新版本的Python(3.4+),则还可以尝试使用pathlib模块以获得更好的,更面向对象的操作路径的方式:

from pathlib import Path

def create(path_str):
    path = Path(path_str)
    path.mkdir(parents=True, exist_ok=True)  # creates parent folders as needed
    with open(path / 'app.py', 'w') as app:  # / operator joins path fragments
        app.write('print("Hello world!")')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM