Monday, September 07, 2020

Python check if file/directory exist

This is a documentation for myself. To check if a file or directory already exists, use the following ways.
 
Check file or directory
import os
os.path.exists('filename')
Check file only
import os
os.path.isfile('filename')
Create the file if not exist
if not os.path.exists('file'): 
 os.mknod('file') 
Create a directory if not exist
if not os.path.exists('file'): 
 os.mkdir('file') 
Please note that the last commands will complain (shows error) if the file or directory 'file' exists. To throw complain, it is better to use `os.makedirs` with argument `exist_ok=True`. It also enables creation of subdirectories with their parent (like bash `mkdir -p`).
os.makedirs('parent-dir/sub-dir', exist_ok=True)
The last one is my favourite since it will create folder if not exist and don't throw error if it is exist.

No comments:

Post a Comment

Your comments here/Silahkan komentar disini...

Related Posts Plugin for WordPress, Blogger...