Python和perl實現批量對目錄下電子書檔案重新命名的代碼分享_python

來源:互聯網
上載者:User

經常會遇到下載的檔案或電子書,名字中間都包含了一些網址資訊,實際使用中由於名字太長不方便,下面的指令碼使用Regex來對目錄下的所有檔案重新命名:
例如:

修改前:[雲棲社區]Mac OS X for Unix Geeks[www.jb51.net].mobi
修改後:Mac OS X for Unix Geeks.mobi

python代碼如下:

複製代碼 代碼如下:

import os
import re

def rename_dir(dir,regex,f):
  if not os.path.isdir(dir) or not os.path.exists(dir) :
    print("The input is not one directory or not exist.")
  for root,subdirs,files in os.walk(dir):
    for name in files:
      oldname = name         
      newname = re.sub(regex,f,name)
      print("Before : " + os.path.join(root,oldname))
      print("After  :  " + os.path.join(root,newname))
      if not name == newname and not os.path.exists(os.path.join(root,newname)):
        os.rename(os.path.join(root,oldname),os.path.join(root,newname))
    for dir in subdirs:
        rename_dir(os.path.join(root,dir))

rename_dir("C:\\Python31\\test","\[.*\](.*)\[www.jb51.net\](.*)",lambda m:m.group(1)+m.group(2))

用perl寫了下,感覺代碼也沒有少寫多少

複製代碼 代碼如下:

use strict;
use warnings;
use File::Find;

my $regex = "\\[.*\\](.*)\\[www.jb51.net\\](.*)";
# $replace doesn't work
my $replace = "\$1\$2";

sub wanted {
 my $name = $File::Find::name;
 if( -f $name){
   my $newname =$name;
   $newname =~ s/$regex/$1$2/;
   print "Before: $File::Find::name\n";
   print "After : $newname\n";
   if( !-e $newname) {
     rename($name, $newname);
   }
 }
}

sub rename_dir{
  my ($dir,) = @_;
  if (!-d $dir || !-e $dir){
    print"The input is not directory or not exist.";
  }
  find(\&wanted, $dir);
}
&rename_dir("c:\\perl\\test");

perl 實現2

複製代碼 代碼如下:

use strict;
use warnings;

my $regex = "\\[.*\\](.*)\\[www.jb51.net\\](.*)";
# $replace doesn't work
my $replace = "\$1\$2";

sub rename_dir{
    my $dir = shift;
    if (!-d $dir || !-e $dir){
      print"The input is not directory or not exist.";
    }
    opendir(DIR, $dir) || die "Cannot opendir $dir.";
    foreach (readdir(DIR)) {
      if ($_ eq '.' || $_ eq '..') {next;}
      my $name = $dir.'/'.$_;
      if(-d $name){
        rename_dir($name);        
        next;
        }
      my $newname =$_;
      $newname =~ s/$regex/$1$2/;
      $newname = $dir.'/'.$newname;
      print "Before : $name\n";
      print "After  : $newname\n";
      rename($name,$newname);
    }
    #closedir(DIR);
}
&rename_dir("c:\\perl\\test");

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.