Zach Tackett
Zach Tackett

Reputation: 614

Python: Find substring in list of string

I have two lists: songs is a list of song titles, filenames is a list of song MP3 files that is generated by running os.listdir().

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.

Upvotes: 0

Views: 541

Answers (2)

trincot
trincot

Reputation: 351328

Here is a version that will maintain the file extension, whatever it was, and will avoid that the same filename is matched twice by deleting it from the filenames array after a match. It also is case insensitive:

for song in songs:
    for i, filename in enumerate(filenames):
        if song.upper() in filename.upper():
            os.rename(filename, song + os.path.splitext(filename)[1])
            del filenames[i]
            break

You could also loop first over the file names, but then the problem can also be that two file names match with the same song, and the rename operation will raise an error on the second. So in that set up you'd better delete the song from the songs list once it has been matched with a file name.

Upvotes: 1

Farid
Farid

Reputation: 11

After having defined the lists as you did, you want to iterate through each file and then check it against every song name. It should look something like this:

for f in filenames:
    for s in songs:
        if s in f:
            os.rename(f,s+".mp3")

This way, the file stays with an mp3 extension as well.

Upvotes: 0

Related Questions