python - 如何使用 YouTube-DL 按播放列表中文件名的标题重命名所有下载的文件?

标签 python json youtube youtube-dl

我尝试下载 youtube channel 中的所有视频并为播放列表创建单独的文件夹。我在 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

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

最佳答案

为了进行健全性检查,让我们看看您的文件夹中当前有什么:

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模块:
  • pathlib ,标准库的一部分。
  • Python 3's pathlib Module: Taming the File System
  • 关于python - 如何使用 YouTube-DL 按播放列表中文件名的标题重命名所有下载的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61722017/

    相关文章:

    Python、Pandas 从数据框创建新数据

    python - Zeromq (pyzmq) ROUTER处理多个客户端的数据以及后续的超时处理

    python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?

    javascript - 如何在特定时间播放嵌入的 youtube iframe 视频?

    android - 如何检查 Youtube 视频是否可嵌入?

    android - 如何打开屏幕并打开youtube应用并保持屏幕打开?

    python - 将值添加到列表并将类型更改为 int

    json - Azure 数据工厂 - 当 JSON key 中有空间时,无法检索 JSON 查找事件输出

    mysql - Laravel:mysql 获取 json 中的所有未读和 15 个最后未读通知

    json - 如何使用 Mongoose 将文档插入只有一个 ObjectID 的集合中?