批量删除两个文件中较小的一个

2024-09-28 18:50:13 发布

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

我正在寻找一种方法来根据下面提到的标准对一堆文件进行批重命名:

文件列表与此类似,应该是字母数字:

  • A201002-1。位置.txt在
  • A201002。位置.txt在
  • A201003-1。位置.txt在
  • A201003。位置.txt ……等等

下面的伪代码与我希望它的行为方式非常接近,但我正在尝试确定sed、awk、python、perl或bash脚本是正确的方法(我正在检查选项,以确定我可能需要深入研究的实现):

for all_files_in_dir:{
  if(currentfile.name is_close_to previousfile.name){  //maybe regex here
    var small_file = find_smaller_file_filename(currentfile.filesize, previousfile.filesize);
    sys.remove(small_file);
  }
}

谢谢你的建议!在


Tags: 文件方法nametxt列表标准字母file
3条回答

我将用Perl发布一个解决方案,只是因为您没有考虑到它的可能性:)

$currentPrefix = "";
$previousFile = "";
while (<*.txt>) {
  /([A-Z]+[0-9]+)-?[0-9]*.loc.txt/;
  if ($1 eq $currentPrefix) {
    if (-s $_ < -s $previousFile) {
      unlink($_);
    } else {
      unlink($previousFile);
      $previousFile = $_;
    }
  } else {
    $currentPrefix = $1;
    $previousFile = $_;
  }
}

以及python中的另一个解决方案:

^{pr2}$

请注意,您需要对文件进行排序,因为glob不会按字典顺序返回它们

import os
import re

def rm_smaller_of(regex, dir):
    for entry in os.listdir(dir):
        if re.match(regex, entry[:9]):
            matches = [(os.stat(f).st_size, f) for f in os.listdir(dir) 
                        if f[:9] == entry[:9]]
            matches.sort(reverse=True)
            for d in matches[1:]:
                os.remove(d[1])

我想这应该行得通。在

^{pr2}$

我的词条:不那么简洁,但希望可读。在

import sys, os
from collections import defaultdict

filenames = sys.argv[1:]

# collect like-named files
groups = defaultdict(set)
for filename in filenames:
    key = filename.split('.')[0].split("-")[0]
    groups[key].add(filename)

# work on each group
for names in groups.values():
    target_name = sorted(names)[0] # or min(names, key=len), or whatever
    largest_file = max(names, key=os.path.getsize)

    os.rename(largest_file, target_name)

    to_remove = names.difference((largest_file, target_name))
    for name in to_remove:
        os.remove(name)

相关问题 更多 >