Python Snippets

Published: Sunday, March 24, 2024
Last Modified: Monday, June 24, 2024

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

 

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

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

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 and download the 1st result as an mp3 audio file
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

 

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...