Build a dictionary comprehension from os.walk

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

I am doing:

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, becomes empty.

There are certain mp3 files in the directory.

Any ideas?

+3


source to share


3 answers


filename[-4] == '.mp3'

checks if the third is the last character '.mp3'

. This makes no sense.

Just use .endswith()

:

filename.endswith('.mp3')

      



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

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

      

I would also convert the filename to lower case before comparing it. You may be able to skip the filenames that are in all the headers.

+7


source


In addition to the already mentioned issue [-4], you keep rewriting source_files_now into a 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 downdown = True and not topdown = 'true'. I removed it because True is the default.

+2


source


You have specified the line a little bit wrong:

>>> s = 'buddyholly.mp3'
>>> s[-4]
'.'
>>> s[-4:]
'.mp3'

      

0


source







All Articles