You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的Pytube库无法将下载文件存入新建目录

问题分析与解决

你的代码核心问题出在os.makedirs的赋值逻辑上:

  • os.makedirs()函数执行成功后返回None,你把这个返回值赋值给了destination,导致后续download(output_path=destination)实际上是把文件下载到了当前脚本运行的工作目录,而非你创建的播放列表文件夹。

修正后的代码

from pytube import Playlist
import os

p = Playlist(input("Enter the URL of the playlist you want to download: \n>> "))
print(f'Downloading: {p.title}')

# 先定义目标目录路径
destination = f'/home/jason/Music/{p.title}'
# 创建目录,exist_ok=True避免目录已存在时报错
os.makedirs(destination, exist_ok=True)

for video in p.videos:
    out_file = video.streams.filter(only_audio=True).first().download(output_path=destination)
    base, ext = os.path.splitext(out_file)
    new_file = base + '.mp3'
    os.rename(out_file, new_file)

关键修改点

  • 先单独定义目标目录的路径字符串,再调用os.makedirs()创建目录,不要把os.makedirs的返回值赋值给destination
  • 添加exist_ok=True参数,防止重复运行脚本时因目录已存在抛出异常

修改后,下载的音频文件会正确存入以播放列表名称命名的文件夹中,你可以在/home/jason/Music/{播放列表名}路径下找到转换后的MP3文件。

内容的提问来源于stack exchange,提问作者Jason Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:09:54