Search code examples
pythonpython-3.xyoutubeyoutube-dlyt

youtube_dl.utils.SameFileError | python, youtube_dl


I am new to youtube_dl and I want to download a youtube playlist in mp3 and after researching a lot, I was able to code this:

import youtube_dl
from time import sleep
# the playlist url
yt_url = input('Enter playlist URL: ')

print('Fetching playlist...')
# Gets the playlist and stores the video info in a list
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})
with ydl:
    result = ydl.extract_info(yt_url, download=False)
    if 'entries' in result:
        video = result['entries']
        
        playlist = []
        for i, item in enumerate(video):
            video = result['entries'][i]
            playlist.append(video)

# Looping the list to download all the videos one by
# one, named as 1.mp3, 2.mp3, 3.mp3 and so on
a = 0
for video in playlist:
    a = a + 1
    ydl_opts = {'outtmpl': f'{a}.mp3'}
    print(f"\nDownloading {video['title']} (https://youtube.com/watch?v={video['id']}) as {a}.mp3...")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(f"https://youtube.com/watch?v={video['id']}")
    sleep(0.5)
    print('Done.')
print('\n\nTask Finished.')

but I keep getting this error:

Downloading otherside (https://youtube.com/watch?v=kK81m-A3qpU) as 1.mp3...
Traceback (most recent call last):
  File "/storage/emulated/0/! workspace/goffy/files/bots/music/a/download.py", line 27, in <module>
    ydl.download(f"https://youtube.com/watch?v={video['id']}")
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/youtube_dl/YoutubeDL.py", line 2063, in download
    raise SameFileError(outtmpl)
youtube_dl.utils.SameFileError: 1.mp3

I don't even have any file named 1.mp3, I only have a file named download.py which contains that code.

Thanks.


Solution

  • Try putting the download URL in a list because that's what the download function expects:

            ydl.download([f"https://youtube.com/watch?v={video['id']}"])
    

    Then this check that raises the SameFileError exception should pass because len(url_list) will be 1.

    At the moment len(url_list) is the number of characters in the URL because it's not wrapped in a list.