好吧,这个很有趣。
真正的问题从这里开始。
download = video_stream[video_quality].download(filepath=save_location, callback=self.Handel_Progress, )
在这里,您正在调用对象的download
函数,该函数将文件位置作为参数但不使用文件名,因为很明显,文件将使用实际名称保存。video_stream
filepath
您的问题的根本原因:
如果查看download
函数的定义,您会发现如果存在同名文件,则根本不会下载该文件。
现在是部分,无论如何,您如何确保它下载:
您需要做两件事:
检查是否存在同名文件,如果存在,则1
在文件名末尾添加扩展名之前。因此,如果abc.mp4
存在,则保存abc1.mp4
. abc.mp4
[我会告诉你当,等存在时如何处理这种情况abc1.mp4
,但现在,让我们回到问题上来。]
如何将文件名(abc1.mp4
)传递给下载方法?
以下代码将同时处理这两个问题。我已添加评论以供您理解。
import os
import re
import pafy
from pafy.util import xenc
# this function is used by pafy to generate file name while saving,
# so im using the same function to get the file name which I will use to check
# if file exists or not
# DO NOT CHANGE IT
def generate_filename(title, extension):
max_length = 251
""" Generate filename. """
ok = re.compile(r'[^/]')
if os.name == "nt":
ok = re.compile(r'[^\\/:*?"<>|]')
filename = "".join(x if ok.match(x) else "_" for x in title)
if max_length:
max_length = max_length + 1 + len(extension)
if len(filename) > max_length:
filename = filename[:max_length - 3] + '...'
filename += "." + extension
return xenc(filename)
def get_file_name_for_saving(save_location, full_name):
file_path_with_name = os.path.join(save_location, full_name)
# file exists, add 1 in the end, otherwise return filename as it is
if os.path.exists(file_path_with_name):
split = file_path_with_name.split(".")
file_path_with_name = ".".join(split[:-1]) + "1." + split[-1]
return file_path_with_name
def Download(self):
video_url = self.lineEdit.text()
save_location = self.lineEdit_2.text()
if video_url == '' or save_location == '':
QMessageBox.warning(self, "Data Error", "Provide a Valid Video URL or save Location")
else:
# video file
video = pafy.new(video_url)
# available video streams
video_stream = video.streams
video_quality = self.comboBox.currentIndex()
# video title/name
video_name = video.title
# take out the extension of the file from video stream
extension = video_stream[video_quality].extension
# fullname with extension
full_name = generate_filename(video_name, extension)
final_path_with_file_name = get_file_name_for_saving(save_location, full_name)
download = video_stream[video_quality].download(filepath=final_path_with_file_name,
callback=self.Handel_Progress, )
如果您遇到任何问题,请告诉我。