如何通过排除字符串来获取所有文件的列表?

How can I get a list of all files by exclude a string?

我有一个装满文件的文件夹:

aaa.sh
bbb.sh
ccc.sh
aaadomain.sh
hhhdomain.sh
yyyydomain.sh
aaadomainasssa.sh

当我这样做时,我得到了所有文件的列表

import glob,os
filelist = glob.glob('*.sh')

但是,我如何排除文件名中包含 domain 作为字符串的所有文件?

我会建议列表理解。

>>> [i for i in glob.glob('*.sh') if 'domain' not in i]
['aaa.sh', 'ccc.sh', 'bbb.sh']

如果您打算遍历 filelist,请使用 filter

for f in filter(lambda x: 'domain' not in x, glob.glob('*.sh')):
    ... # do something with f

或者,使用列表理解

filelist = [x for x in glob.glob('*.sh') if 'domain' not in x]