Search code examples
pythonfiledirectoryfile-exists

how can I find whether there is any txt file in a directory or not with Python


I would like to find that whether there is any file exists in a specific directory or not with using python.

Something like this;

if os.path.exists('*.txt'):
   # true --> do something
else:
   # false --> do something

Solution

  • You can use glob.glob with wildcards and check whether it returns anything. For instance:

    import glob
    if glob.glob('*.txt'):
        # file(s) exist -> do something
    else:
        # no files found
    

    Note that glob.glob return a list of files matching the wildcard (or an empty list).