pythondirectory

How do I check if a directory exists in Python?


How do I check if a directory exists in Python?


Solution

  • Use os.path.isdir for directories only:

    >>> import os
    >>> os.path.isdir('new_folder')
    True
    

    Use os.path.exists for both files and directories:

    >>> import os
    >>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
    False
    

    Alternatively, you can use pathlib:

     >>> from pathlib import Path
     >>> Path('new_folder').is_dir()
     True
     >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
     False