This article will show you some examples of how to use the python os.path
module exists
function to check file/folder existence. And how to create directory and subdirectory with python os
module mkdir
and makedirs
function.
1. How to check file or folder existence in python.
- First of all, you can use the
exists
function in the Pythonos.path
module to determine whether the directory exists or not. If the directory or file exists, theos.path.exists
function will return True, if the directory does not exist, then it will return False.>>> import os >>> >>> os.path.exists('./Desktop') True >>> >>> >>> os.path.exists('./test') False
2. How to create a directory in python.
- To create a directory, you can first get the current directory with the
os
modulegetcwd
function, and then splice the directory name and create a folder using the pythonos.mkdir
function.>>> import os >>> >>> cwd = os.getcwd() >>> >>> cwd '/Users/songzhao' >>> >>> target_dir = cwd +'/test' >>> >>> os.path.exists(target_dir) False >>> >>> target_dir '/Users/songzhao/test' >>> >>> os.mkdir(target_dir) >>> >>> os.path.exists(target_dir) True
- The python
os
modulemkdir
function can also create an empty folder with an absolute path.>>> import os >>> >>> os.mkdir('/Users/songzhao/test') >>> >>> os.path.exists('/Users/songzhao/test') True
- If you want to create a multi-level directory, you need to use the function
makedirs
in the pythonos
module.>>> import os >>> >>> os.mkdirs('/Users/songzhao/test/a/b/c') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'os' has no attribute 'mkdirs' >>> >>> >>> os.makedirs('/Users/songzhao/test/a/b/c') >>> >>> os.path.exists('/Users/songzhao/test/a/b/c') True