Skip to main content
 首页 » 编程设计

python之根据模式 : Python 识别一组文件和进程

2025年05月04日14bhlsheji

我的要求是,如果我在文件名中发现了一个特定的模式,那么我需要删除属于该组的相应文件组。例如,下面是我拥有的文件组:

file1.infile_inprogress_2015033 
file1.infile_rsn_20150330022431 
file1.infile_err_20150330022431 
file2.infile_03_29_2015_05:08:46 
file2.infile_03_29_2015_05:09:56 
file3.infile_20150330023214 

我需要在文件名中搜索的模式是:"inprogress"。因此在上面的列表中,我需要删除以下文件:

file1.infile_inprogress_2015033 
file1.infile_rsn_20150330022431 
file1.infile_err_20150330022431 

因为上面的列表在标识符“infile”之前有相同的文件名(“file1”)。

到目前为止,我只能列出文件:

 filelist = (glob.glob('C:\\CIRP\\Velocidata\\Test\\*')) 
 for file in filelist: 
  filenamecopied = os.path.basename(file) 
  if fnmatch.fnmatch(filenamecopied,"*Inprogress*"): 
   print ('Delete the group of files ') 
  else: 
   print ('skip this file') 

请您参考如下方法:

操作系统 walk是一个更好的选择(更容易阅读)然后过滤文件名。

import os 
top = 'C:\\CIRP\\Velocidata\\Test\\' 
 
# Getting the list of all files 
for root, dirs, files in os.walk(top): 
 
    # Filtering for group names that are 'Inprogress' 
    groups_in_progress = [] 
    for name in files: 
        if 'Inprogress' in name: 
            group = name[0:name.lower().find('infile')] 
            groups_in_progress.append(group.lower()) 
 
    # Delete the files where a group is in progress 
    for name in files: 
        for group in groups_in_progress: 
            if name.lower().startswith(group): 
                os.remove(os.path.join(root, name)) 

您可以使用字典和各种优化,但这是最直接的。