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 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
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
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
Top comments (0)