我是 Python 新手,过去只使用过 PHP 5(很多年前)。作为一个初学者项目,我想我应该使用 pytube 制作一个 YouTube 下载器,让您选择是下载最高质量的视频还是仅下载 .mp3 格式的音频。
好吧,我陷入了最后一部分:将扩展名更改为 .mp3。
我想要一个我可以理解的简单而优雅的解决方案,但我们将不胜感激。
我尝试使用 os.rename() 但不确定如何使其工作。
from pytube import YouTube
import os
yt = YouTube(str(input("Enter the URL of the video you want to download: \n>> ")))
print("Select download format:")
print("1: Video file with audio (.mp4)")
print("2: Audio only (.mp3)")
media_type = input()
if media_type == "1":
video = yt.streams.first()
elif media_type == "2":
video = yt.streams.filter(only_audio = True).first()
else:
print("Invalid selection.")
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> "))
video.download(output_path = destination)
if media_type == "2":
os.rename(yt.title + ".mp4", yt.title + ".mp3")
print(yt.title + "\nHas been successfully downloaded.")
编辑:
昨天我尝试时它只是卡在最后一部分上,但我又试了一次,过了一会儿我收到了此错误消息:
Traceback (most recent call last):
File "Tubey.py", line 42, in <module>
os.rename(yt.title + ".mp4", yt.title + ".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: "Cristobal Tapia de veer - DIRK GENTLY's original score sampler - cut 3.mp4" -> "Cristobal Tapia de veer - DIRK GENTLY's original score sampler - cut 3.mp3"
文件已下载但未重命名。
最终编辑:(可能)
我终于让它工作了,这主要归功于 J_H。谢谢你容忍我的无能,你是一个圣人。 这是最终解决问题的完整代码(以防将来遇到此问题的其他人也遇到类似的问题):
from pytube import YouTube
import os
yt = YouTube(str(input("Enter the URL of the video you want to download: \n>> ")))
print("Select download format:")
print("1: Video file with audio (.mp4)")
print("2: Audio only (.mp3)")
media_type = input(">> ")
if media_type == "1":
video = yt.streams.first()
elif media_type == "2":
video = yt.streams.filter(only_audio = True).first()
else:
print("Invalid selection.")
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
out_file = video.download(output_path = destination)
if media_type == "2":
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
print(yt.title + " has been successfully downloaded.")
我打算将其变成一个长期项目,并随着我学到的越多,用更多的功能扩展脚本,但现在我很满意。再次感谢。
最佳答案
看来您的代码只有在用户输入以斜杠结尾时才能正常工作。
使用os.path.join()
将目标目录与文件名组合起来。
使用此表达式默认为空 .
,当前目录:
destination = str(input(">> ")) or '.'
编辑:
我希望您的假设(我们可以从标题预测输出文件规范)是正确的。
但不是。
例如,yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')
获取标题以 'M/V'
结尾的 PSY 音乐视频。
然而 .download()
将(相当合理地)构造一个仅包含 'MV'
的文件名,不带斜线。
您不应该尝试预测输出文件规范。
相反,您应该存储 .download()
的返回值,
所以你会确切地知道正确的文件规范是什么。
以下是将输出重命名为常量文件名的示例:
>>> out_file = yt.streams.first().download()
>>> os.rename(out_file, 'new.mp3')
>>>
或者,如果您愿意,可以将其重命名为os.path.join('/tmp', 'new.mp3')
。
您可能还希望使用 splitext
解析扩展名:
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
您可能会发现 only_audio
标志是减少视频消耗的带宽的便捷方法,
如果您只想获取音轨:
yt.streams.filter(only_audio=True).all()
2021 年编辑:
您不必使用os
,
您现在可以使用:
video.download(output_path=destination, filename=input("Enter file name (without extension): "))
关于python - 如何自动重命名从 pytube 下载的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348346/