首页 > 解决方案 > Python: "invert" fnmatch to match one file name?

问题描述

This has to be simple; how do I exclude one file using fnmatch from a printed list generated by os.listdir?

This python script only lists the index.php file; I want to exclude index.php and list all other .php files. If I remove if fnmatch.fnmatch(entry, 'index.php'): I get a list of all files including index.php. Is it possible to "invert" fnmatch?

import os, fnmatch

listOfFiles = os.listdir('.')  
pattern = "*.php"  
for entry in listOfFiles:  

 if fnmatch.fnmatch(entry, 'index.php'):

    if fnmatch.fnmatch(entry, pattern):
            print (entry)

标签: python

解决方案


import os, fnmatch

listOfFiles = os.listdir('.')  
pattern = "*.php"  
for entry in listOfFiles:   
    if entry != "index.php" and fnmatch.fnmatch(entry, pattern):
            print(entry)

推荐阅读