Python和perl实现批量对目录下电子书文件重命名的代码分享
例如:
修改前:[脚本之家]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");
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
专题推荐
-
独孤九贱-php全栈开发教程
全栈 170W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
-
玉女心经-web前端开发教程
入门 80W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
-
天龙八部-实战开发教程
实战 120W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论