理解为什么这个python代码随机工作

xav*_*ier 5 python python-3.x

我正在编写一个小脚本,从声音文件中获取元数据,并创建一个具有所需值的字符串.我知道我做错了但是我不确定为什么,但这可能是我迭代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])
Run Code Online (Sandbox Code Playgroud)

我随机得到了想要的结果或错误:

结果:

1967 Ravi Shankar & Yehudi Menuhin West Meets East Raga: Puriya Kalyan
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

Pet*_*ood 5

如果在元数据"title"之前"album"出现,则album永远不会被初始化."album"可能根本不存在.

由于您没有删除album每个轨道的值,如果轨道先前已"album"定义,则下一个未定义的轨道"album"将使用前一个轨道的值.

为每个曲目添加一个空白值(如果这对你合理).

查看build_name值是字符串列表,因此默认值应为['']:

for sound_file in files:
    artist = album = title = ['']
Run Code Online (Sandbox Code Playgroud)

但是,build_name如果元数据乱序,您仍然无法在调用之前获取值.

你需要build_name(artist, album, title)离开循环:

for (key, value) in metadata.items():
    ...  # searching metadata
build_name(artist, album, title)
Run Code Online (Sandbox Code Playgroud)

  • @xavier,作为一般经验法则:首先解析,稍后解释 (2认同)