Python和perl实现批量对目录下电子书文件重命名的代码分享

永远对生活充满希望,对于困境与磨难,微笑面对。多看书,看好书,少吃点,吃好的。要有梦想,即使遥远。开朗的心情,这很重要。

经常会遇到下载的文件或电子书,名字中间都包含了一些网址信息,实际使用中由于名字太长不方便,下面的脚本使用正则表达式来对目录下的所有文件重命名:
例如:

修改前:[]Mac OS X for Unix Geeks[www.haodaima.com].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.haodaima.com\](.*)",lambda m:m.group(1)+m.group(2))

用perl写了下,感觉代码也没有少写多少


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

my $regex = "\\[.*\\](.*)\\[www.haodaima.com\\](.*)";
# $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(\&, $dir);
}
&rename_dir("c:\\perl\\test");

perl 实现2


use strict;
use warnings;

my $regex = "\\[.*\\](.*)\\[www.haodaima.com\\](.*)";
# $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");

以上就是Python和perl实现批量对目录下电子书文件重命名的代码分享。愿我们上半年所有的遗憾,都是下半年惊喜的铺垫,加油吧。更多关于Python和perl实现批量对目录下电子书文件重命名的代码分享请关注haodaima.com其它相关文章!

标签: 重命名