国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python和perl實(shí)現(xiàn)批量對(duì)目錄下電子書文件重命名的代碼分享

2020-02-23 06:11:55
字體:
供稿:網(wǎng)友

經(jīng)常會(huì)遇到下載的文件或電子書,名字中間都包含了一些網(wǎng)址信息,實(shí)際使用中由于名字太長不方便,下面的腳本使用正則表達(dá)式來對(duì)目錄下的所有文件重命名:
例如:

修改前:[武林站長站]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 = "http://[.*//](.*)//[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 實(shí)現(xiàn)2

代碼如下:
use strict;
use warnings;

my $regex = "http://[.*//](.*)//[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;}

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 鹰潭市| 忻州市| 西华县| 沁阳市| 醴陵市| 喀喇沁旗| 大兴区| 安龙县| 沂南县| 博客| 无为县| 新巴尔虎左旗| 平邑县| 东辽县| 云梦县| 保靖县| 连平县| 会同县| 姜堰市| 木里| 隆昌县| 宜丰县| 晋城| 凤冈县| 建昌县| 昂仁县| 怀远县| 墨脱县| 清涧县| 鄂托克前旗| 大城县| 高淳县| 都昌县| 当阳市| 乌鲁木齐县| 阳山县| 大洼县| 余干县| 股票| 互助| 新巴尔虎右旗|