Skip to content

Instantly share code, notes, and snippets.

@sht
Last active February 28, 2026 17:03
Show Gist options
  • Select an option

  • Save sht/5f02d44d1019252d503a8b39a61f2bea to your computer and use it in GitHub Desktop.

Select an option

Save sht/5f02d44d1019252d503a8b39a61f2bea to your computer and use it in GitHub Desktop.
Python script for downloading youtube videos as mp3 files
#!/usr/bin/env python3
import yt_dlp, os, sys, re
def sanitize_filename(filename):
# Replace problematic characters including fullwidth pipe with regular pipe
filename = filename.replace('|', '|')
# Remove or replace other problematic characters
filename = re.sub(r'[<>:"|?*]', '_', filename)
return filename
def download_youtube_audio(url, output_dir):
# Configuration for audio download
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': os.path.join(output_dir, '%(title)s'),
'noplaylist': True,
'verbose': True,
'restrict_filenames': True, # Restrict to safe characters
}
try:
# Create output folder if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Download process
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
print(f"Downloading: {url}")
ydl.download([url])
print(f"Audio saved in '{output_dir}' folder!")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 youtube_to_mp3.py <output_folder>")
print("Example: python3 youtube_to_mp3.py .")
print(" python3 youtube_to_mp3.py /path/to/music")
sys.exit(1)
output_dir = sys.argv[1]
url = input("YouTube URL: ").strip()
if url:
download_youtube_audio(url, output_dir)
else:
print("Invalid URL! Example: https://www.youtube.com/watch?v=dQw4w9WgXcQ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment