我正在編寫一個小的腳本,從一個聲音文件中獲取元數據並創建一個具有所需值的字符串。我知道我做錯了什麼,但我不知道爲什麼,但這可能是我迭代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
既然你沒有'隨機導入',我會感到驚訝,如果你的代碼工程*隨機*雖然它可能工作*意外* –