How To Create A Folder With Python

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.

  1. First of all, you can use the exists function in the Python os.path module to determine whether the directory exists or not. If the directory or file exists, the os.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.

  1. To create a directory, you can first get the current directory with the os module getcwd function, and then splice the directory name and create a folder using the python os.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
    
  2. The python os module mkdir 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
    
  3. If you want to create a multi-level directory, you need to use the function makedirs in the python os 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
    

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky