Python: Difference between revisions
Line 65: | Line 65: | ||
[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"> | ||
def ensure_dir_exists( | def ensure_dir_exists(dir_path): | ||
if not os.path.exists( | if not os.path.exists(dir_path): | ||
try: | try: | ||
os.makedirs( | os.makedirs(dir_path) | ||
except OSError as exc: # Guard against race condition | except OSError as exc: # Guard against race condition | ||
if exc.errno != errno.EEXIST: | if exc.errno != errno.EEXIST: | ||
raise | 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")) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
====Copying or moving a file or folder==== | ====Copying or moving a file or folder==== |