使用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
相关产品推荐
相关产品推荐

