How to Parse JSON, TXT, and CSV Files in Python

This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.

Easy Python 3.9+ Aug 9, 2026 Files & data 16 views 0 copies

Python code

37 lines
Python 3.9+
import json
from pathlib import Path

def parse_json_file(filepath):
    """Read and parse a JSON file, returning its contents."""
    path = Path(filepath)
    with path.open('r', encoding='utf-8') as f:
        return json.load(f)

def parse_txt_lines(filepath):
    """Read a text file and return non-empty stripped lines."""
    path = Path(filepath)
    with path.open('r', encoding='utf-8') as f:
        return [line.strip() for line in f if line.strip()]

def parse_csv_file(filepath):
    """Read a CSV file and return list of rows as lists."""
    import csv
    path = Path(filepath)
    with path.open('r', encoding='utf-8', newline='') as f:
        reader = csv.reader(f)
        return [row for row in reader]

if __name__ == "__main__":
    sample_data = '{"name": "Alice", "age": 30, "city": "Berlin"}'
    Path("sample.json").write_text(sample_data)
    
    Path("sample.txt").write_text("first line\n\nsecond line\n  third line  ")
    
    Path("sample.csv").write_text("id,name\n1,Alice\n2,Bob\n")
    
    print("JSON:", parse_json_file("sample.json"))
    print("TXT:", parse_txt_lines("sample.txt"))
    print("CSV:", parse_csv_file("sample.csv"))
    
    for f in ["sample.json", "sample.txt", "sample.csv"]:
        Path(f).unlink()

Output

stdout
JSON: {'name': 'Alice', 'age': 30, 'city': 'Berlin'}
TXT: ['first line', 'second line', 'third line']
CSV: [['id', 'name'], ['1', 'Alice'], ['2', 'Bob']]

How it works

This script defines three helper functions that use pathlib.Path for clean file handling. parse_json_file uses json.load to convert JSON content into a Python dictionary. parse_txt_lines strips each line and filters out empty ones, returning a clean list. parse_csv_file leverages the csv.reader to parse rows into lists, preserving the data structure as strings.

Common mistakes

  • Forgetting to specify `encoding='utf-8'` can cause UnicodeDecodeError on non-ASCII files.
  • Using `json.loads` on a file object instead of `json.load` leads to TypeError.
  • Not using `newline=''` for CSV files can produce extra blank lines in output on Windows.

Variations

  1. Use `pandas.read_csv()` for more advanced CSV parsing with built-in type inference.
  2. Use `json.loads(Path(filepath).read_text())` to parse a JSON file without opening the file manually.

Real-world use cases

  • Reading configuration files in JSON format to initialize application settings.
  • Processing log files by extracting and cleaning non-empty lines for analysis.
  • Importing tabular data from CSV exports to load into a database or for reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.