Python Snippets

Published: Sunday, March 24, 2024
Last Modified: Monday, July 22, 2024

I always find myself writing these snippets over and over again. Maybe they already exist in some libraries I haven’t discovered yet?

Make Current Directory File Path

import os
def make_path(*filepaths):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), *filepaths)

Current Datetime TZ

import datetime, pytz
def get_current_datetime(timezone_str='America/Toronto'):
    utc_now = datetime.datetime.now()
    timezone = pytz.timezone(timezone_str)
    now_tz = utc_now.replace(tzinfo=pytz.utc).astimezone(timezone)
    return now_tz

Search YouTube, Download First Result as MP3

import os
searches = """Saturnalias - JSUK
SHOEGAZER - spiral"""
os.chdir(os.path.dirname(__file__))
for search in searches.split('\n'):
    search = search.strip()
    try:
        command = f"""yt-dlp -f 'ba' -x --audio-format mp3 --playlist-item 1 ytsearch:"{search}" -o "./songs/%(title)s___%(id)s.%(ext)s" """
        os.system(command)
    except:
        pass

Vocaroo Download

import os
d = {
    'name': 'https://voca.ro/string',
}
for name, link in d.items():
    print(name)
    os.system(f'yt-dlp {link} -o {name}.mp3')

Random 2 Decimal Float

import random
def get_random_float(N, M):
    assert N <= M
    return round(random.uniform(N, M), 2)

I’ll add more here as time goes on, and I work on my projects. Feel free to share yours too, and I can include them in this post!

Comment
Optional
No comments yet...