创建目录和文件-不能按预期工作(pathlib,.mkdir,.touch)

问题描述 投票:0回答:1

我正在尝试从Python列表中创建一些目录和文件。

我对for循环的期望是,它将检查列表中是否存在该路径,并确定该路径是否为文件路径。如果是这样,则创建任何必要且不存在的目录,然后创建文件。如果该路径指向一个不存在的目录,请创建该目录。如果路径已经存在,则无论它指向目录还是​​文件,都应打印一条消息,指出无需采取进一步措施。运行代码时,仅从路径列表中创建项目[0]和[1]。我究竟做错了什么? -预先感谢您的反馈!

paths = [
    directory / "test1.py",
    directory / "test2.py",
    directory / "FOLDERA" / "test3.py",
    directory / "FOLDERA" / "FOLDERB" / "image1.jpg",
    directory / "FOLDERA" / "FOLDERB" / "image2.jpg",
    ]



 for path in paths:
    if path.exists() == False:
        if path.is_file() == True:
            path.parent.mkdir()
            path.touch()
        if path.is_dir() == True:
            path.mkdir(parent=True)
    if path.exists() == True:
        print(f"No Action {path} Already Exists!")
python python-3.x mkdir pathlib
1个回答
0
投票

逻辑失败,因为路径检查is_file()和is_dir(),并且因为两者在开始时都是假的。

for path in paths:
    print("path is ", path)
    if path.exists() == False:
        if path.is_file() == True: #--- Since the file is not there so is_file() will return False 
            path.parent.mkdir()
            path.touch()
        elif path.is_dir() == True: #--- Since the directory is not there is_dir() will return False
            path.mkdir(parent=True)
    if path.exists() == True:
        print(f"No Action {path} Already Exists!")

相反,如果要检查特定文件类型的条件,请尝试在if块中包括以下逻辑,还应包括自定义逻辑。

for path in paths:
    print("path is ", path)
    if path.exists() == False:
        if "." in str(path) and path.is_file()==False : #---Assuming it is a file if it contains .  
            # Check if parent exists
            if not path.parent.exists(): 
                path.parent.mkdir()
            path.touch()
        elif path.is_dir()==False:
            if not path.parent.exists(): 
                path.parent.mkdir()
            path.mkdir(parent=True)

    if path.exists() == True:
        print(f"No Action {path} Already Exists!")
© www.soinside.com 2019 - 2024. All rights reserved.