Check if file is a file or directory:
import os
if os.path.isfile('./path/to/file.txt'):
print("Is File")
if os.path.isdir("./path/to/dir/"):
print("Is Directory")
if not os.path.exists('./test1/test2'):
os.makedirs('./test1/test2')
To create a path:
import os
path = os.path.join('root-dir', 'parent-dir', 'file.txt')
To make directories recursively:
import os
if not os.path.exists('./test1/test2'):
os.makedirs('./test1/test2')
Alternatively:
from pathlib import Path
Path('./test3/test4').mkdir(parents=True, exist_ok=True)
Split a file path into dir and file:
import os
head, tail = os.path.split('/path/to/file.txt')
print(head) # '/path/to'
print(tail) # 'file.txt'
Get the extension from path
import os
path, ext = os.path.splitext('/path/to/file.tar.gz')
print(path) # '/path/to/file.tar'
print(ext) # '.gz'