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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With