我正在编写一个小的脚本,从一个声音文件中获取元数据并创建一个具有所需值的字符串。我知道我做错了什么,但我不知道为什么,但这可能是我迭代if的方式。当我运行代码:了解为什么这个Python代码随机工作
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
加上'专辑= “”''前循环for'如果 – Arman
你看看'if'在'for'循环块,一些迭代将分配'专辑';有些尝试使用“专辑”。如果导致尝试使用“专辑”的条件发生在导致分配“专辑”的条件之前,那么您尝试使用未分配的变量。 – khelwood
既然你没有'随机导入',我会感到惊讶,如果你的代码工程*随机*虽然它可能工作*意外* –