首页 > 解决方案 > Python tempfile 使用 for 循环返回 NotADirectoryError

问题描述

所以我正在创建一个不和谐的机器人,它会选择 5 首随机歌曲,使用 youtube-dl 下载并播放它们。编码:

# Function to play music
async def radio(count, voiceClient, textChannel):
    randomSong = songs[random.randint(0, len(songs)-1)]
    # Open a temporary directory to stop downloaded files being saved
    with tempfile.TemporaryDirectory() as tempDir:
        # Use youtube-dl to get the metadata
        ydlOptions = {
            "format": "bestaudio/best",
            "outtmpl": f"{tempDir}/%(id)s.%(ext)s",
        }
        with YoutubeDL(ydlOptions) as ydl:
            realLinkRaw = ydl.extract_info(randomSong, download=True)
            videoID = realLinkRaw["id"]
            videoExtension = realLinkRaw["ext"]
        # Test if its the first song so a message can be displayed
        if count == 0:
            # First song so output a message describing it
            title = realLinkRaw["title"]
            await textChannel.send(f"Up next, {title}")
        # Play the song
        tempFileName = f"{tempDir}/{videoID}.{videoExtension}"
        voiceClient.play(FFmpegPCMAudio(tempFileName))
        # Wait for the duration of the song before repeating
        await asyncio.sleep(realLinkRaw["duration"])


# Function to loop continuously and run the main program
async def mainProg(voiceClient, textChannel):
    # Create infinite loop to run main program
    while True:
        # Output a random radio message
        await textChannel.send(radioLines[random.randint(0, len(radioLines)-1)])
        # Play 5 random songs
        for count in range(5):
            await radio(count, voiceClient, textChannel)

但是,目前在第一首歌曲播放完毕后,我收到此错误:

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\jacka\\AppData\\Local\\Temp\\tmpzodsgvvw\\SH_pDjcQx2w.m4a'

整个回溯: https ://pastebin.com/2HVJvS5m

标签: pythonpython-3.xtemporary-filesyoutube-dl

解决方案


推荐阅读