Iterate through two lists, check for matches and then rename

China☆狼群 提交于 2019-12-11 06:45:36

问题


Ok, so I have two lists; one is a list of song titles, the other is a list of files that is generated by running os.listdir(), which will be song mp3 files.

UPDATED

songs = ['The Prediction', 'Life We Chose', 'Nastradamus', 'Some of Us Have Angels', 'Project Windows', 'Come Get Me', "Shoot 'em Up", 'Last Words', 'Family', 'God Love Us', 'Quiet Niggas', 'Big Girl', 'New World', 'You Owe Me', 'The Outcome']

Each song is unicode

filenames = ['Nas - Big Girl.mp3', 'Nas - Come Get Me.mp3', 'Nas - God Love Us.mp3', 'Nas - Life We Chose.mp3', 'Nas - Nastradamus.mp3', 'Nas - New World.mp3', "Nas - Shoot 'Em Up.mp3", 'Nas - Some of Us Have Angels.mp3', 'Nas - The Outcome.mp3', 'Nas - The Prediction.mp3', 'Nas Feat. Bravehearts - Quiet Niggas.mp3', 'Nas Feat. Ginuwine - You Owe Me.mp3', 'Nas Feat. Mobb Deep - Family.mp3', 'Nas Feat. Nashawn - Last Words.mp3', 'Nas Feat. Ronald Isley - Project Windows.mp3']

Each filename is a string

I want to be able to look at the songs list, if one of the items from the songs list matches inside the filenames list, rename the file to that of the song.

Does that make sense?


回答1:


Basically it looks like this:

import os

for song in songs:
    for filename in filenames:
        if song.lower() in filename.lower():  # lower() just in case
            os.rename(filename, song + '.mp3')

If you need anything else, please ask.



来源:https://stackoverflow.com/questions/42053017/iterate-through-two-lists-check-for-matches-and-then-rename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!