Python youtube_dl更改输出名称



我正在尝试建立一个不和谐的音乐机器人,我使用youtube_dl下载歌曲。我想把它们保存在一个目录里,这样我就不用每次都下载了。但是我想更改目录中的歌曲名称。

我知道我必须在outtmpl中更改一些内容,但这只是给我歌曲的youtube名称:

ydl_opts = {
'outtmpl': f'./project/audio/%(title)s.%(ext)s', #Output directory
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])

当我用:'outtmpl':f'./project/audio/{songname}',替换outtmpl时,它给了我错误信息:下载错误:错误:音频转换失败:文件:mp3:无效参数

我知道这是一个老问题,但我现在正在做同样的事情,并这样做:

import os
import youtube_dl
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
name = info.get('title')
id = info.get('id')
ydl.download([id])
for file in os.listdir():
if file.startswith(name) and file.endswith('.mp3'):
os.rename(file, your_file_name)

对于像我一样寻找答案的人来说,这是我想到的。

list = [
{'title': 'foo', 'url': 'www.youtube.com/foo'}, 
{'title': 'bar', 'url': 'www.youtube.com/bar'},
#etc
]
i = 1
for d in list:
ydl_opts = {
'outtmpl': '~/AutoYouTube/' + f'{i:02d}' + '. ' + d['title'] + '.%(ext)s',
'restrictfilenames': True
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([d['url']])
i += 1

对我来说,这感觉更"干净"了。比BigAgg的解决方案要好,因为它首先为文件提供所需的名称,而不是在下载后重命名文件。也就是说,在循环中重复调用ydl.download()而不是将单个列表传递给函数可能会有一些低效率,其中最重要的是ydl的自动编号中断,必须使用i递增来重新构建。

尝试print您的outtmpl,以确保它包含您所期望的。PEP建议在f-string中使用{variable}而不是%(ext)s

f'./project/audio/{title}.{ext}'

最新更新