【问题标题】:How can I get a list of all files by exclude a string?如何通过排除字符串来获取所有文件的列表?
【发布时间】:2017-11-07 03:57:13
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: python operating-system glob


    【解决方案1】:

    如果您打算迭代 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]
    

    【讨论】:

      【解决方案2】:

      我会建议一个列表理解。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多