我正在编写一个从声音文件中获取元数据的小脚本,并创建一个包含所需值的字符串。我知道我做错了什么但是我不知道为什么,但这可能是我迭代if的方式。当我运行代码时:
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])
我随机得到了所需的结果或错误:
结果:
1967 Ravi Shankar & Yehudi Menuhin West Meets East Raga: Puriya Kalyan
错误:
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
答案 0 :(得分:5)
如果"title"
位于元数据"album"
之前,那么album
将永远不会被初始化。 "album"
可能根本不存在。
由于您没有为每个曲目留出album
的值,如果曲目之前已定义"album"
,则下一曲目不会定义{{1}将使用上一个曲目的值。
为每首曲目添加一个空白值(如果这对你合理)。
查看"album"
值是字符串列表,因此默认值应为build_name
:
['']
但是,如果元数据乱序,您仍然无法在调用for sound_file in files:
artist = album = title = ['']
之前获取值。
您需要将build_name
移出循环:
build_name(artist, album, title)