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 File Into Words
“””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) as input_file:
content = input_file.readlines()
content = [word.strip() for word in content]
return content
Read JSON File into Dict
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