简体   繁体   中英

glob on non existant file with pattern matching

I have this snippet which basically checks if a file exists with pattern matching. Please help me with a better way to do this.

import glob

for afile in glob.glob( "*.non-existant-file" ):
    print afile 
try:
    if afile:
        print "OK"
except:
    print "Come back later"

To test is a file of a given name exist, the easiest is to use os.path.isfile .

But if you just have the pattern, looking for them can indeed be done with glob . glob.glob will return a (possibly empty) list of names of files matching the pattern. If you just want to test they exist, just look at the length of this list:

if glob.glob(pattern):
    print('There are some files matching the pattern.')
else:
    print('No files matching the pattern.')

Try this:

#this will print out all the files which end with the extension py.
for filenames in glob.glob(r"*.py"):
  print(filenames)

#this will print out all the files which end with the extension py. and have "n" in their name.
for filenames in glob.glob(r"*n*.py"):
   print(filenames)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM