Search code examples
pythonpython-3.xmkdirpathlib

Creating Directories and Files - Not working as expected (pathlib, .mkdir, .touch)


I'm trying to create some directories and files from a list in Python.

The expectation I had of my for loop is that it would check to see if the path exists in the list, determine if it is a file path or not. If so create any necessary and unexistent directories and then the file. If the path points to a directory that doesn't exist create it. If a path already exists, regardless of it pointing to a directory or file, print a message stating that no further action is required. When I run my code, only item [0] and [1] are created from the paths list. What am I doing wrong? - Thanks in advance for the feedback!

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

Solution

  • The logic fails because of the the path checks for is_file() and is_dir() and since both will be false at the begining.

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

    Instead try the below logic and also include custom logic in the if block if you want the condition to be checked for specific file types.

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