The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Create Directories And Folders In Python

TODO: Pull subtitle into page object

Basic mkdir:

code_start_default_section code_end_default_section

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Create Directories And Folders In Python

-- p

Basic mkdir:

-- code/
-- python

from pathlib import Path 

dir_path = 'path/to/new/directory'

Path(dir_path).mkdir(parents=True, exist_ok=True)

-- /code

-- p

TODO: Confirms this works on windows

-- p

Make a directory for a file path so it's ready to go. That is, you send a file path and it makes the parent directory for that file if it doesn't already exist. Possibly overkill? Should also probably move the  `file_path = Path(file_path)` into the function. And maybe keep it as a single argument function without named parameters.

-- code/
-- python

import os
    from pathlib import Path
    
    def mkdir_p_for_file(*, file_path):
        dir_path = os.path.dirname(file_path)
        Path(dir_path).mkdir(parents=True, exist_ok=True)
    
            
    file_path = '/Users/alans/Desktop/kill_dir/level2/test_file.txt'
    file_path = Path(file_path)
    
    mkdir_p_for_file(file_path=file_path)

-- /code

-- p

Make a directory for a given filepath. Includes a touch feather if you want to touch the file which doesn't make a lot of sense, but still. (Make another one without that. )

-- code/

import os
from pathlib import Path

def mkdir_p_for_file(*, file_path, touch=False):
    dir_path = os.path.dirname(file_path)
    Path(dir_path).mkdir(parents=True, exist_ok=True)
    if touch:
        Path(file_path).touch()
        
file_path = '/Users/alans/Desktop/kill_dir/level2/test_file.txt'
# Optionally make it a path
file_path = Path(file_path)

mkdir_p_for_file(file_path=file_path, touch=True)

-- /code


-- categories
-- Python

-- metadata
-- date: 2020-11-01 13:22:00
-- id: 264kgjsm
-- status: scratch
-- type: post
-- SCRUBBED_NEO: false
-- site: aws