经常会遇到下载的文件或电子书,名字中间都包含了一些网址信息,实际使用中由于名字太长不方便,下面的脚本使用正则表达式来对目录下的所有文件重命名:
例如:
修改前:[]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");
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 廖也欧《面朝大海》[Hi-Res][24bit 48kHz][FLAC/分轨][170.14MB]
- s13T1夺冠五人名单都有谁 s13T1夺冠五人名单一览
- 英雄联盟T1战队队长都有谁 T1战队所有队长介绍
- skt历届战队成员都有哪些 skt历届战队成员名单盘点
- 妙音唱片《大热唱片3》[WAV+CUE]
- 费玉清《跟着地球旋转》滚石时代经典复刻[正版原抓WAV+CUE]
- 罗文甄妮-射雕英雄传(AMCD)(限量版)[WAV+CUE]
- 《巫师4》定档2025再添佐证:参演人员曝光 老将回归
- 辣眼睛 美女COS《黑神话:悟空》比基尼版金池长老
- 外媒称PS5pro违背承诺:《蜘蛛侠2》根本没法4K60帧
- 令晴 Lynn《The Make》[320K/MP3][44.47MB]
- 令晴 Lynn《The Make》[Hi-Res][24bit 48kHz][FLAC/分轨][295.42MB]
- 雷婷《移情别恋HQⅡ》头版限量编号[低速原抓WAV+CUE][1G]
- FUNDAMENTAL.1989-感觉号渡轮【SONY】【WAV+CUE】
- 上山安娜.1986-上山安娜【EMI百代】【WAV+CUE】