My go-to Python snippets

kdipippo

Kathryn DiPippo

Posted on April 24, 2024

My go-to Python snippets

This is a blog post just for me, but it's all of the Python snippets I repeatedly look up or reference from other parts of my codebase.

Snippets List

  • Read File into Words
  • Read JSON File into Dict
  • Read CSV File into Dict List
  • Read YAML File into Dict

Read File Into Words

def read_file_into_words(filename: str) -> list[str]:
    """Parse a text file into a 2D list of words, i.e.
        "This is an example file with
        multiple lines of text" becomes
        ["This is an example file with", "multiple lines of text"].

    Args:
        filename (str): Path to text file.

    Returns:
        list[list[str]]: 2D list of string words.
    """
    with open(filename, "r", encoding="utf-8") as input_file:
        content = input_file.readlines()
    content = [word.strip() for word in content]
    return content
Enter fullscreen mode Exit fullscreen mode

Read JSON File into Dict

import json

def read_json_file_into_dict(filename: str) -> dict:
    """Parse a JSON file into a dictionary.

    Args:
        filename (str): Path to JSON file.

    Returns:
        dict: Dictionary representation of JSON file contents.
    """
    with open(filename, "r", encoding="utf-8") as json_file:
        content = json.load(json_file)
    return content
Enter fullscreen mode Exit fullscreen mode

Read CSV File into Dict List

import csv

def read_csv_file_into_dict_list(filename: str) -> list[dict]:
    """Parse a CSV file into a list of dictionaries.

    Args:
        filename (str): Path to CSV file.

    Returns:
        dict: List of dictionary representations of CSV file contents.
    """
    content = []
    with open(filename, newline="", encoding="utf-8") as csv_file:
        reader = csv.DictReader(csv_file)
        for row in reader:
            content.append(dict(row))
    return content
Enter fullscreen mode Exit fullscreen mode

Read YAML File into Dict

def read_yaml_into_dict(filename: str) -> dict:
    """Return content of YAML file as dictionary.

    Args:
        filename (str): Path to YAML file to read and return.

    Returns:
        dict: Content of YAML file as dictionary.
    """
    with open(filename, "r", encoding="utf-8") as yaml_file:
        yaml_contents = yaml_file.read()
    return yaml.safe_load(yaml_contents)
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
kdipippo
Kathryn DiPippo

Posted on April 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024