DEV Community

Kathryn DiPippo
Kathryn DiPippo

Posted on • Edited on

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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more