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
有帮助吗?

解决方案

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

其他提示

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

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

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top