Python: Difference between revisions

236 bytes added ,  13 January 2020
Line 130: Line 130:




====Create Directory if it doesn't exist====
====Create or Delete Directory/Folders====
[https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output Reference]
[https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output Reference]
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import os, shutil, time
import os.path as path
# Or os.makedirs(path, exist_ok=True)
# Or os.makedirs(path, exist_ok=True)
def ensure_dir_exists(dir_path):
def ensure_dir_exists(dir_path):
Line 147: Line 150:
# or
# or
ensure_dir_exists(os.path.dirname("new_dir/my_file.txt"))
ensure_dir_exists(os.path.dirname("new_dir/my_file.txt"))
# Delete an empty directory
os.rmdir(dir_path)
# Delete a empty or non-empty directory
shutil.rmtree(dir_path)
# Wait until it is deleted
while os.path.isdir(dir_path):
  time.sleep(0.01)
</syntaxhighlight>
</syntaxhighlight>