私は、サウンドファイルからメタデータを取得し、目的の値を持つ文字列を作成する小さなスクリプトをコーディングしています。私は何か間違っていることを知っていますが、私はなぜそれがわからないのですが、おそらく私が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
が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
あなたは 'for'ループ、一部では' if'ブロックを見れば 'for'ループ – Arman
'前に「」= 'アルバムを追加iterationsは 'album'を割り当てます。いくつかは 'アルバム'を試してみてください。 'album'を使用しようとする条件が' album'割り当てに至る条件の前に起こる場合、未割り当て変数を使用しようとしています。 – khelwood
あなたは 'import random'を持っていないので、あなたのコードが*ランダムに*動作するかもしれませんが、予期せず* –