2012-03-06 202 views
0

直接在那里。
将文件重命名为其文件夹名称

我有一个电影文件夹里面有子文件夹。
在这些子文件夹中(电影名称)是我想要重命名为somename.nfosubfoldername.release和从somename.mkvsubfoldername.mkv的实际电影文件。

Folderstructure是这样的:
完整/ La.Haine.1995.1080p.BluRay.DTS.x264-DON/LH-don.mkv
完整/ La.Haine.1995.1080p.BluRay.DTS.x264-DON /lh-don.nfo

,想自动地其重命名为这样:

完整/ La.Haine.1995.1080p.BluRay.DTS.x264-DON/La.Haine.1995.1080p.BluRay。 DTS.x264-DON.mkv
complete/La.Haine.1995.1080p.BluRay.DTS.x264-DON/La.Haine.1995.1080p.BluRay.DTS.x264-DON.release

我的图书馆在Mac OS上,上面有Perl和Python。我可以轻松地修改任何脚本,但需要一些关于如何设置和读取文件夹名称作为某种变量的指导。

欢迎所有的指导:-)
谢谢你的阅读。

+6

也许我们这样做反过来:你试试吧,我们适应。 – 2012-03-06 14:14:19

回答

2

下面是Perl中的例子。

你可能会想要修改这个,但它显示了如何使用opendir/readdir,这是你所需要的,我认为。它可以做得更短,但可能不是那么好找为Python版本,所以我去了冗长,(希望)明确:)

#!/usr/bin/env perl 
# 
use warnings; 
use strict; 

my $rootdir = 'your/root/dir'; 
opendir(my $rootdh, $rootdir) || die; 
foreach my $dir (readdir $rootdh) { 
    # skip over the special directories . and .. 
    if ($dir =~ m/^\./) { 
     next; 
    } 
    # only want directories 
    next unless (-d "$rootdir/$dir"); 
    opendir(my $dh, "$rootdir/$dir") || die; 
    foreach my $file (readdir $dh) { 
     if ($file =~ m/^\./) { 
      next; 
     } 
     # only want files this time 
     next unless (-f "$rootdir/$dir/$file"); 
     my $extension = $file; 
     $extension =~ s/.*\.//g; 
     print "$rootdir/$dir/$file", " will be renamed to: ", "$rootdir/$dir/$dir.$extension", "\n"; 
     # uncomment this when you're ready! 
     #rename "$rootdir/$dir/$file" "$rootdir/$dir/$dir.$extension"; 
    } 
} 
+0

这工作**完美**,它只在重命名行中缺少'逗号':-),现在我需要弄清楚将扩展nfo重命名为释放。 – discofris 2012-03-06 16:09:50

2

通常你可以使用glob.glob()这种东西。但既然你想通过文件夹递归走,你可能想使用os.walkfnmatch组合来代替:

import os 
import fnmatch 

for root, dirnames, filenames in os.walk('/start/dir/'): 
    for filename in fnmatch.filter(filenames, '*.mkv'): 
    # do your rename here