在附加以停止重复之前读取CSV

2024-04-29 05:17:11 发布

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

该项目包括使用YTAPI在播放列表中列出所有youtube视频,然后下载视频。 Im使用CSV文件,通过将视频id附加到CSV,确保不再下载相同的视频(相同的视频id)

with open('video-id.csv','a+',newline='') as csv_file:
    writer = csv.writer(csv_file)
    reader = csv.reader(csv_file)

youtube api代码

for video in videos["items"]:
    video_id = video["contentDetails"]["videoId"]

    if video_id in reader:
        print('duplicate')
    
    elif video_id not in csv_file:
        # converts the videoID to a link shich can be used by pytube module
        video_url = "https://www.youtube.com/watch?v=" + video_id

        # defines url for the pytube module
        video = YouTube(video_url)

        # only returns 'streams' which are soley 'audio' using the 'first' one in the list (highest audio bitrate)
        video_stream = video.streams.filter(only_audio=True).first()

        print('Downloading',video_title + '...')

        video_stream.download()

        # appends id to csv to ensure the video is not downloaded again
        writer.writerow({video_id})

CVS文件已成功追加,但每次运行脚本时都会追加相同的视频id,我正在努力找到一种方法来检查csv文件是否有匹配的视频id,以防止发生这种情况

CVS文件:

hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4

Tags: 文件csvthetoinid视频youtube
1条回答
网友
1楼 · 发布于 2024-04-29 05:17:11

希望下面的评论能有所帮助:

  1. 当您第一次读取像video_id in reader这样的文件时,然后要重新读取它,您需要使用seek()方法将“滑块”移动到文件的开头:

    csv_file.seek(0,0) # offset=0, whence=0 (beginning of the file)
    
  2. 在读卡器(video_id in reader)中检查视频id时,请注意读卡器中的项是一个列表:

    for item in reader:
      print(item)
    

    将返回:

    ['hi9_oyKAAds']
    ['b3T4b3GCRk4']
    ...
    
  3. 如果使用csv_文件(在代码中)进行迭代,请注意它包含video_id not in csv_file个字符,如下所示:

    for item in csv_file:
      print(repr(item))
    

    会回来的

    'hi9_oyKAAds\r\n'
    'b3T4b3GCRk4\r\n'
    

相关问题 更多 >