Created
October 26, 2021 03:28
-
-
Save jeremy-rutman/5b4cb6bda14f59e0577716b47832a09d to your computer and use it in GitHub Desktop.
python func to create missing dirs, recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def ensure_dir(path): | |
''' | |
Create missing dirs recursively unless something coincides with file, or no permissions | |
:param path:desired path , to be created | |
:return:True if desired path created, False if not | |
''' | |
if not os.path.isdir(path): | |
print(path+' does not exist, creating') | |
head = path | |
totail = [] | |
while(1): | |
head,tail = os.path.split(head) | |
totail.append(tail) | |
if os.path.isdir(head): | |
print(head+' exists') | |
break | |
if head is None or head == '' : | |
print('malformed path') | |
return False | |
totail.reverse() | |
for t in totail: | |
newdir = os.path.join(head,t) | |
if os.path.isfile(newdir): | |
print('file with this name exists, not creaating dir') | |
return False | |
try: | |
os.mkdir(newdir) | |
except PermissionError: | |
print('permission denied for making '+str(newdir)) | |
return False | |
head = newdir | |
return True | |
else: | |
return True | |
ensure_dir('homeqwd/jqwderemy/smorb/blorb') | |
ensure_dir('/homeqwd/jqwderemy/smorb/blorb') | |
ensure_dir('/home/jeremy/smorb/blorb') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment