7

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
erolkaya84
  • 1,769
  • 21
  • 28

4 Answers4

7

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).

isedev
  • 18,848
  • 3
  • 60
  • 59
  • 1
    actually, AshwiniChaudhary's solution is more efficient (doesn't generate an unused list). – isedev Mar 01 '14 at 12:05
5

You can use glob.iglob with next:

import glob
if next(glob.iglob('*.txt'), False):
     #do something
else:
     #do something else

Here if glog.iglob returns an empty iterator then the default value False will be used.

or as @user2357112 suggested in comments, we can simply use any as it returns False for an empty iterable.:

if any(glob.iglob('*.txt')):
     #do something
else:
     #do something else
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

os.listdir() will get you everything that's in a directory - files and directories

import os
if not os.listdir(dir):
    #do something
else:
    #do something
Sanjay
  • 1,078
  • 11
  • 15
  • This seems not correct. It does not distinct a directory with .txt files from a directory with only other files. – Kjell Apr 12 '22 at 20:16
0

For those getting here from google there is another solution you can use for checking if a glob is empty or not.

The previous answers are sufficient in themselves, however you can also determine the amount of files returned by a glob using len(), and use that as a comparison.

if(len(glob.glob('*.txt')) == 0):
    #Glob has no files
else:
    #Continue

This will let you confirm if the glob does, or does not, have files. This also lets you confirm that the glob has more than or less than a specific quantity of files, should you need to do so.

Mr Arca9
  • 41
  • 2
  • This seems redundant - although I must admit that if you know nothing about what glob does, this is more immediately readable. I'd be curious to see whether there are time differences. – Lou Nov 24 '20 at 16:19