Check if a directory contains a file using python



You can find out if a directory is empty or not in Python with

# Python program to check
# if the directory contains the file

 

 

import os

 
# directory path

directoryPath = "D: / Pycharm projects / Python.Engineering / Nikhil"

 
# Compare returned list with empty list

if os.listdir (directoryPath) = = []:

print ( "No files found in the directory." )

else :

print ( "Some files found in the directory." )

Exit:

 Some files found in the directory. 
  • Comparing the length of the returned list with 0
    We can get the length of the list using Python`s len () method. If the length of the returned list is zero, then the directory is empty, otherwise it is not.

    # Python checker
    # the directory contains the file

     

     

    import os

     
    # directory path

    directoryPath = "D: / Pycharm projects / Python.Engineering / Nikhil"

     
    # Check list length

    if len (os.listdir (directoryPath)) = = 0 :

    print ( "No files found in the directory." )

    else :

      print ( "Some files found in the directory." )

    Exit:

     Some files found in the directory. 
  • Comparing the Boolean value of a list
    In the above method, we used an explicit comparison of the length of the list. We now go in a more Pythonic way using the truth check of a value. An empty list evaluates to false in Python.

    # Python checker
    # directory is empty

     

     

    import os

     
    # directory path

    directoryPath = "D: / Pycharm projects / Python.Engineering / Nikhil"

     
    # Checking the boolean value of the list

    if not os.listdir (directoryPath):

    prin t ( "No files found in the directory." )

    else :

    print ( " Some files found in the directory. " )

    Exit :

     Some files found in the directory. 
  • Full source code:

    # Python checker
    # directory is empty

     

    import os

     

      
    # Function to check if the directory
    # contains a file or not

    def isEmpty (directoryPath):

     

    # Check if the directory exists or not

    if os.path.exists (directoryPath):

     

    # Checking if the directory is empty or not

    if len (os.listdir (directoryPath)) = = 0 :

    return "No files found in the directory."

    else :

    return "Some files found in the directory."

    else :

    return   "Directory does not exist!"

     
    # Driver code

      
    # Valid directory

    directoryPath = "D: / Pycharm projects / Python.Engineering / Nikhil"

    print ( "Valid path:" , isEmpty (directoryPath))

      
    # Invalid directory

    directoryPath = "D: / Pycharm projects / Python.Engineering / Nikhil / GeeksforGeeks"

    print ( "Invalid path:" , isEmpty (directoryPath))

    Exit :

     Valid path: Some files found in the directory. Invalid path: Directory does not exist!