2011-09-10 73 views
0

中我經常發現自己在一個情況下,我有一個包含它們按照一定的文件命名規則命名的文件夾,我不得不通過他們去手動將其重命名爲我想要的一個。費力重複的任務。文件由公約重命名 - 所有的文件夾

E.g. 01_artist_name_-_album_title_-_song_title_somethingelse.mp3 - >Song_Title.mp3

因此刪除某些信息位,用空格替換下劃線和大寫。不只是音樂,這只是一個例子。

我一直在思考自動使用Python這個任務。基本上我希望能夠輸入起始約定和我想要的約定,並將其重命名爲全部。

理想我希望能夠做到這一點在Windows上的Python,但我有一個Ubuntu的機器,如果它是更容易在bash做(或Python在UNIX上)我可以用這個。

如果任何人都可以闡明我如何解決這個問題(建議IO Python命令讀取文件夾的內容並重命名文件 - 在Windows上,以及如何從文件名中剝離信息並進行分類它,也許使用正則表達式?)我會看看我能做什麼,並隨着進展而更新。

回答

1

對於您的特殊情況:

import glob, shutil, os.path 

# glob.glob returns a list with all pathes according to the given pattern 
for path in glob.glob("music_folder/*.mp3"): 

    # os.path.dirname gives the directory name, here it is "music_folder" 
    dirname = os.path.dirname(path) 

    # example: 01_artist_name_-_album_title_-_song_title_somethingelse.mp3 
    # split returns "_song_title_somethingelse.mp3" 
    interesting = path.split("-")[2] 

    # titlepart is a list with ["song", "title"], the beginning "_" and the 
    # 'somehting' string is removed by choosing the slice 1:-1 
    titlepart = interesting.split("_")[1:-1] 

    # capitalize converts song -> Song, title -> title 
    # join gluest both to "Song_Title" 
    new_name = "_".join(p.capitalize() for p in titlepart)+".mp3" 

    # shutil.move renames the given file 
    shutil.move(path, os.path.join(dirname, new_name)) 

如果你想使用正則表達式,你必須更換:

 m=re.search(".*-_(\S+_\S+)_.*",path) 
    if m is None: 
     raise Exception("file name does not match regular expression") 
    song_name = m.groups()[0] 
    titlepart = song_name.split("_") 
+0

感謝您的幫助。它使我朝着正確的方向前進。我用拆分來分離所有信息位,然後循環遍歷我想要的位,並將它們全部大寫,用空格分隔它們的字串,刪除最後的空間並添加文件擴展名。使用os.rename(舊的,新的)來重命名。 –