基于模式识别一组文件和进程:Python

2024-09-28 21:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

Tags: 文件列表文件名模式file1infileglobfile2
3条回答

有几个问题:

  1. 它们是否总是按顺序排列,就像您列出的那样,或者它们是否会突然出现 按不同的顺序排列?你知道吗
  2. 他们有任何常规格式的功能(比如filexxx)。在前面)?你知道吗
  3. “进行中”部分总是在其他文件之前出现吗?你知道吗

如果我假设文件名格式是一堆字母或数字,然后是“.”,然后是更多的字符,它们以随机顺序出现,我会这样做:

  1. 浏览创建要删除的文件前缀列表。你知道吗
  2. 再次检查,删除前缀中的文件。你知道吗

有点像这样:

filelist = (glob.glob('C:\\CIRP\\Velocidata\\Test\\*'))
deleteList = set()
for f in filelist:
    if "inprogress" in f.lower():     #Checks if inprogress is in the filename
        deleteList.add(f[:f.find(".")])  #Adds base of filename
print deleteList
for f in filelist:
    if f[:f.find(".")] in deleteList:
        print "Delete:",f
    else:
        print "Do not delete:",f

我还没有做实际的删除代码,但你可以检查是否这是捕捉你的一切。我使用了简单的字符串函数,而不是re来捕捉基于您所说的文件名。如果没有,请回复以上问题的答案!你知道吗

OSwalk是一个更好的选择(更容易阅读),然后根据文件名进行筛选。你知道吗

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))

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

你需要^{}。在文档中,os.unlink用于

Remove (delete) the file path.

if子句中添加几行

# This if will check for "InProgress"
if fnmatch.fnmatch(filenamecopied,"*Inprogress*"):
    filegroup = filenamecopied.split('.')[0]   # get the file group                                                   
    for i in filelist:                         # Iterate through the files
        # This if will check for "file1" or "file2" etc
        if (i.startswith(filegroup)):          # if i is of same group
             os.unlink(i)                      # Delete it

相关问题 更多 >