ckdanny
2/27/2020 - 2:20 PM

Check if directory exists and Safely create a nested directory

Check if directory exists and Safely create a nested directory

# Ref: https://tecadmin.net/python-check-file-directory-exists/

# 1. Python – Check if File Exists

# isfile() – function check if given input file exists and is a file not directory.
# exists() – function check if given input file exists. It doesn’t matter its a file or directory.

import os.path

print(os.path.isfile("/etc/hosts"))  # True
print(os.path.isfile("/etc"))  # False
print(os.path.isfile("/does/not/exist"))  # False
print(os.path.exists("/etc/hosts"))  # True
print(os.path.exists("/etc"))  # True
print(os.path.exists("/does/not/exist"))  # False

# OR

from pathlib import Path

fileName = Path("/etc/hosts")

if fileName.is_file():
    print("File exist")
else:
    print("File not exist")

# 2. Python – Check if File Readable

import os.path

if os.path.isfile('/etc/hosts') and os.access('/etc/hosts', os.R_OK):
    print("File exists and is readable")
else:
    print("Either file is missing or is not readable")

# 3. Python – Check if Link File

import os.path

if os.path.isfile("/etc/hosts") and os.path.islink("/etc/hosts"):
    print("This is a link file")
else:
    print("This is actual file")

# 4. Python – Create Directory if not Exists

# Use os.path.exists to check if any directory exists or not and use os.makedirs to create a directory.
# Below example will create directory /tmp/newdir if not exists.

if not os.path.exists('/tmp/newdir'):
    os.makedirs('/tmp/newdir')
# https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory
import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
    os.makedirs(directory)