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

PyTube下载音频为MP4格式,自定义MP3文件名报OSError22如何解决?

问题修复方案

报错原因

  • 文件名拼接逻辑错误:你写的link.title+'mp3'缺少后缀分隔符.,会生成不符合预期的[标题]mp3格式文件名
  • 非法字符冲突:YouTube视频标题常包含Windows系统禁止作为文件名的字符(\ / : * ? " < > |等),直接传入会触发无效参数报错

修复代码

你不需要额外用到临时文件夹,利用pytube download方法返回文件路径的特性,下载后直接重命名即可,完整修改后代码如下:

import os
from pytube import YouTube

def clean_filename(filename):
    # 替换所有Windows文件名非法字符为下划线
    illegal_chars = r'\/:*?"<>|'
    for c in illegal_chars:
        filename = filename.replace(c, '_')
    return filename

link='https://www.youtube.com/watch?v=KrhPrPK2owA'
link=YouTube(link)
print('Title:',link.title+'\n'+'Views:',link.views)
streams=link.streams.filter(type='audio')
kbps_list=[]
itag_list=[]
print('Available Kbps: ',end='')
for s in streams:
    i=s.itag
    s=s.abr
    if s not in kbps_list:
        kbps_list.append(s)
        itag_list.append(i)
        print(s,end=' ')
reso=input('\nEnter Kbps to download: ')
if reso not in kbps_list:
    print('This Kbps is not available')
    from sys import exit
    exit()
reso=kbps_list.index(reso)
final=streams.get_by_itag(itag_list[reso])
print('Downloading...')
# 下载并获取原始文件路径
original_file = final.download('G:/Downloaded Videos/')
# 生成清理后的mp3格式文件名
file_dir = os.path.dirname(original_file)
raw_name = os.path.splitext(os.path.basename(original_file))[0]
new_file = os.path.join(file_dir, f"{clean_filename(raw_name)}.mp3")
# 重命名文件
os.rename(original_file, new_file)
print('Successfully Downloaded!')

可选方案:下载时直接指定文件名

如果你想在调用download方法时直接传入mp3文件名,提前清理标题即可:

clean_title = clean_filename(link.title)
final.download('G:/Downloaded Videos/', filename=f"{clean_title}.mp3")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:54:01