如何使用YouTubeDL根据播放列表中文件名的标题重命名所有下载的文件?

2024-05-16 20:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图下载youtube频道中的所有视频,并为播放列表创建单独的文件夹。我在youtube dl中使用了以下代码

youtube-dl -f 22 --no-post-overwrites -ciw -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/channel/UCYab7Ft7scC83Sk4e9WWqew/playlists

所有视频文件都已下载。但你不能把它们都玩。原因是该文件没有名称和扩展名。只有索引号。这是截图

enter image description here

这是由代码中的一个小错误引起的。在我看到它之后。更正后的代码应如下所示

youtube-dl -f 22 --no-post-overwrites -ciw -o '%(uploader)s/%(playlist)s/%(playlist_index)s-%(title)s.%(ext)s https://www.youtube.com/channel/UCYab7Ft7scC83Sk4e9WWqew/playlists

一旦代码正确,它将按如下方式下载

enter image description here

这就是我现在想要的观点。 所有这些文件都应重命名为播放列表。但无需重新下载所有视频文件。 我下载了json文件以获取文件信息。由于我对编码有着基本的了解,我不知道如何使用它

enter image description here

我不能再下载了。很难说出一个。这需要很多时间。因为有很多文件。我该怎么做


Tags: 文件no代码httpsindextitleyoutubepost
1条回答
网友
1楼 · 发布于 2024-05-16 20:19:27

要进行健全性检查,请查看文件夹中当前的内容:

from pathlib import Path

folder_path = '/Users/kevinwebb/Desktop/test_json'

p = Path(folder_path).glob('**/*')
files = [x for x in p if x.is_file()]

print(files)

输出:

[PosixPath('/Users/kevinwebb/Desktop/test_json/02-Ranking Factor.info.json'),
 PosixPath('/Users/kevinwebb/Desktop/test_json/02'),
 PosixPath('/Users/kevinwebb/Desktop/test_json/01'),
 PosixPath('/Users/kevinwebb/Desktop/test_json/01-How to do- Stuff in Science.info.json')]

现在,我们将专门查找json文件,获取索引和名称,并重命名文件

# Grab all files that have json as extension
json_list = list(Path(folder_path).rglob('*.json'))
# Split on the first occurance of the dash
index = [x.name.split("-",1)[0] for x in json_list]
# Split again on the dot
names = [x.name.split("-",1)[1].split(".",1)[0] for x in json_list]

folder_p = Path(folder_path)

# zipping puts the two lists side by side
# and iteratively goes through both of them
# one by one
for i,name in zip(index,names):
    # combine the folder name with the id
    p = folder_p / i

    # rename file with new name and new suffix
    p.rename((p.parent / (i + "-" + name)).with_suffix('.mp4'))

您现在应该看到新命名的mp4文件

来自pathlib模块的更多信息:

相关问题 更多 >