How to rename downloaded audio files extensions to mp3 with python

Viewed 267

currently I'm trying to download youtube music videos as audio files based on artists name and song titles and after downloading all the videos I'm trying to rename all the audio files from .webm or .mp4 extension to .mp3. But it seems I'm facing some errors to change the file names and extensions to .mp3. My code basically doesn't rename the name and extensions of the audio files. Can anybody help me to rename the downloaded files as .mp file ?

Here is my code .........

import os
from requests import get
from yt_dlp import YoutubeDL

YDL_OPTIONS = {'format' : 'bestaudio/best', 'noplaylist' : 'True'}
filename=[]
old=[]
positions=[]
def search(arg, index):
  with YoutubeDL(YDL_OPTIONS) as ydl:
    try:
      get(arg)
    except:
      song =   ydl.extract_info(f"ytsearch:{arg}", download=True)['entries'][0]
    else:
      song =   ydl.extract_info(arg, download=True)

oldpath = song['title'] + '[' + song['id'] + ']' + '.' + song['ext'] 
old.append(oldpath)
newpath = f"{song['title']}.mp3"
if os.path.isfile(oldpath):
  os.rename(f"{oldpath}",newpath)
  filename.append(str(newpath))
else:
  filename.append(str(newpath))
  positions.append(index)


return filename , positions, old


title = (dataset['Title'] + " " + dataset['Artist']).tolist()
for index, arg in enumerate(title):
   filename, positions, old = search(arg, index=index )

Here oldpath = originally file downloaded with this format newpath = to which format i want to rename it title contains song title and artist name, (like: Falling - Harry Styles). There is another thing that is if i check filename there it successfully shows all audio files names with .mp3, but if i try to run the audio file with renamed name and .mp3, it gives me this error "FileNotFoundError: [Errno 2] No such file or directory: 'The Weeknd - Blinding Lights (Official Video).mp3'"

1 Answers

Are you certain the files are being downloaded to the intended location? Assuming you got the filename correct, the other option is that the directory is incorrect.

Parameter outtmpl allows you to define a template for a file name and path. Check the docs of the original youtube-dl for the details.

Here's an example:

ydl_options = {
    'outtmpl': '~/Music/%(extractor_key)s/%(extractor)s-%(id)s-%(title)s.%(ext)s'
}

ydl = yt_dlp.YoutubeDL(ydl_opts)
Related