Python: Difference between revisions

100 bytes added ,  16 October 2019
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(filename):
def ensure_dir_exists(dir_path):
     if not os.path.exists(os.path.dirname(filename)):
     if not os.path.exists(dir_path):
         try:
         try:
             os.makedirs(os.path.dirname(filename))
             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====