Misc

Posted: less than 1 minute read

Check operating system

def os_check():
    from sys import platform

    if platform == "darwin":
        print("macOS")
    elif platform == "win32":
        print("Windows")
    elif platform == "linux" or platform == "linux2":
        print("Linux")
    else:
        print("Oops! Something went wrong.")

Check if path is a file or directory

def path_checker(path):
    from pathlib import Path
    path = Path(path)

    if path.exists():
        if path.is_dir():
            print(f"'{path}' is directory")
        else:
            if path.is_file():
                print(f"'{path}' is a file")
        return True

    else:
        print(f"'{path}' does not exist.")
        return False

Return string of list (or list-like string) elements with Oxford comma.

def oxford(x):
    if isinstance(x, str):
        x = x.replace(" ", "").replace(",", "")
    else:
        x = [str(item) for item in x]
    if len(x) == 0:
        return
    if 0 < len(x) < 3:
        return ", ".join(x)
    else:
        first_part = x[:-1]
        last_part = x[-1]
        return ", ".join(first_part) + ", and " + last_part

Combine two lists to a dictionary

months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
months_alpha = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Des']
dictionary = [{'label': x,'value': y} for x, y in zip(months, months_alpha)]

Leave a comment