Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary comprehension from os.walk

I am trying to create a dictionary of all mp3 files where the key is the mp3 filename and the value is the filepath for that file.

I do:

for root, dirs, files in os.walk(rootDir, topdown='true'):
    source_files_now = {filename:root for filename in files if filename[-4] == '.mp3'}
    print(source_files_now);

But the dictionary, source_files_now ends up being empty.

There are definetly mp3 files in the directory.

Any ideas?

like image 606
dublintech Avatar asked Jan 15 '23 04:01

dublintech


2 Answers

filename[-4] == '.mp3' checks whether the third-to-last character is '.mp3'. That doesn't really make sense.

Just use .endswith():

filename.endswith('.mp3')

If you want to fix your code, slice the string so that the slice includes the other characters:

filename[-4:] == '.mp3'

I'd also convert the filename to lowercase before comparing it. You might end up skipping filenames that are in all caps.

like image 110
Blender Avatar answered Jan 21 '23 18:01

Blender


In addition to the [-4] issue already mentioned, you keep overwriting source_files_now in your for loop. Initialize it above the loop and just add to it instead of using the dict comprehension.

source_files_now = {}
for root, dirs, files in os.walk(rootDir):
    for filename in files:
        if filename.endswith('.mp3'):
            source_files_now[filename] = os.path.join(root, filename)

It doesn't break your script, but it should be topdown=True, not topdown='true'. I removed it because True is the default.

like image 24
tdelaney Avatar answered Jan 21 '23 18:01

tdelaney