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...