Understanding why this Python code works randomly

I am coding a little script that gets metadata from a sound file and creates a string with the required values. I know that I am doing something wrong, but I'm not sure why, but this is probably the way I repeat if's. When I run the code:

import os, mutagen XPATH= "/home/xavier/Code/autotube/tree/def" DPATH="/home/xavier/Code/autotube/tree/down" def get_meta(): for dirpath, directories,files in os.walk(XPATH): for sound_file in files : if sound_file.endswith('.flac'): from mutagen.flac import FLAC metadata = mutagen.flac.Open(os.path.join(dirpath,sound_file)) for (key, value) in metadata.items(): #print (key,value) if key.startswith('date'): date = value print(date[0]) if key.startswith('artist'): artist = value #print(artist[0]) if key.startswith('album'): album = value #print(album[0]) if key.startswith('title'): title = value #print(title[0]) build_name(artist,album,title) # UnboundLocalError gets raised here def build_name(artist,album,title): print(artist[0],album[0],title[0]) 

I get the desired result or error, randomly:

RESULT:

 1967 Ravi Shankar & Yehudi Menuhin West Meets East Raga: Puriya Kalyan 

ERROR:

 Traceback (most recent call last): File "<stdin>", line 39, in <module> File "<stdin>", line 31, in get_meta build_name(artist,album,title) UnboundLocalError: local variable 'album' referenced before assignment 
+5
source share
1 answer

If "title" precedes "album" in metadata, then album will never be initialized. "album" may not exist at all.

As you do not obscure the album value for each track, if the track previously had "album" , then the next track that does not define "album" will use the previous track value.

Give it an empty value for each track (if that is reasonable for you).

Looking at build_name , the values ​​are lists of strings, so the default value should be [''] :

 for sound_file in files: artist = album = title = [''] 

However, you still will not get the value before calling build_name if the metadata is out of order.

You need to move build_name(artist, album, title) from the loop:

 for (key, value) in metadata.items(): ... # searching metadata build_name(artist, album, title) 
+5
source

Source: https://habr.com/ru/post/1241019/


All Articles