Python: Difference between revisions

368 bytes removed ,  13 January 2020
Line 130: Line 130:




====Create or Delete Directory/Folders====
====Directories====
[https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output Reference]
Create, Move, and Delete directories or folders
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import os, shutil, time
import os, shutil, time
import os.path as path
import os.path as path


# Or os.makedirs(path, exist_ok=True)
# Create a directory
def ensure_dir_exists(dir_path):
os.makedirs("new_dir", exist_ok=True)
    if not os.path.exists(dir_path):
# or os.makedirs(os.path.dirname("new_dir/my_file.txt"), exist_ok=True)
        try:
            os.makedirs(dir_path)
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise
 
 
# Example usage to create new_dir folder
ensure_dir_exists("new_dir")
# or
ensure_dir_exists(os.path.dirname("new_dir/my_file.txt"))


# Delete an empty directory
# Delete an empty directory
os.rmdir(dir_path)
os.rmdir(dir_path)
# Delete an empty or non-empty directory
# Delete an empty or non-empty directory
shutil.rmtree(dir_path)
shutil.rmtree(dir_path)