I'm coding a little script that gets metadata from a sound file and creates a string with the desired values. I know I'm doing something wrong but I ain't sure why, but it's probably the way I am iterating the 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 an 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
To generate random number in Python, randint() function is used. This function is defined in random module.
Python doesn't convert its code into machine code, something that hardware can understand. It actually converts it into something called byte code. So within python, compilation happens, but it's just not into a machine language. It is into byte code (.
Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python Virtual Machine. This is a similar approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM).
If "title"
comes before "album"
in the meta data then album
will never be initialised. "album"
may not exist at all.
As you don't blank out the value of album
for each track, if a track has previously had "album"
defined then the next track which doesn't define "album"
will use the previous track's value.
Give it a blank value for each track (if that's reasonable to you).
Looking at build_name
the values are lists of strings, so the default should be ['']
:
for sound_file in files:
artist = album = title = ['']
However, you will still not get values before calling build_name
if the metadata is out of order.
You need to move build_name(artist, album, title)
out of the loop:
for (key, value) in metadata.items():
... # searching metadata
build_name(artist, album, title)
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