Skip to main content

A clean, extensible file reader library supporting CSV, JSON, TXT, XLSX, PDF, and DOCX formats. Developed and tested on Python 3.12.8 (recommended). Other versions within 3.9–3.12 should also work.

Project description

Unified File Reader

A clean, extensible Python library for reading multiple file formats with a unified API. Built following Clean Code and Clean Architecture principles.

Features

  • Unified API: Single read_file() function for all supported formats
  • Multiple Formats: CSV, JSON, TXT, XLSX, PDF, DOCX
  • Clean Architecture: Modular, testable, and maintainable codebase
  • Extensible: Add new file readers without modifying core logic
  • Type-Safe: Full type hints for better IDE support
  • Well-Tested: Comprehensive test suite with high coverage
  • Production-Ready: PyPI packaging, logging, and error handling

Requirements

Developed and tested on Python 3.12.8 (recommended). Other versions within 3.9–3.12 should also work.

  • pip (latest version recommended)
  • Virtual environment tool (python -m venv)

See requirements.txt for the exact dependency versions used with Python 3.12.8.

Installation

From PyPI

pip install unified-file-reader

From source (development setup)

# Clone the repository
git clone https://github.com/praveen9392/unified-file-reader.git
cd unified-file-reader

# Create a virtual environment (recommended)
python -m venv .venv

# Activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (cmd)
.venv\Scripts\activate.bat
# macOS / Linux
source .venv/bin/activate

# Install runtime + dev dependencies
pip install -e ".[dev]"

# Alternatively, to match exact versions from this repo
pip install -r requirements.txt

Quick Start

from unified_file_reader import read_file

# Read any supported file format
data = read_file("data.csv")
data = read_file("config.json")
data = read_file("document.pdf")
data = read_file("spreadsheet.xlsx")

Supported Formats

Format Extension Return Type Notes
CSV .csv List[Dict] Returns list of dictionaries
JSON .json Any Preserves JSON structure
TXT .txt str Returns plain text content
Excel .xlsx List[Dict] Returns list of dictionaries
PDF .pdf str Extracts all text content
DOCX .docx str Extracts all paragraph text

Architecture Overview

unified_file_reader/
├── api.py                 # Public API entry point
├── registry.py            # Reader registry (dependency inversion)
├── exceptions.py          # Custom exceptions
├── interfaces/
│   └── base_reader.py     # Abstract reader contract
├── readers/               # Concrete implementations
│   ├── csv_reader.py
│   ├── json_reader.py
│   ├── txt_reader.py
│   ├── excel_reader.py
│   ├── pdf_reader.py
│   └── docx_reader.py
├── utils/
│   └── file_utils.py      # Utility functions
└── config/
    └── supported_formats.py

Design Principles

  • Single Responsibility Principle (SRP): Each reader handles one format
  • Open/Closed Principle (OCP): Add new readers without modifying existing code
  • Liskov Substitution Principle (LSP): All readers implement the same interface
  • Interface Segregation Principle (ISP): Minimal, focused interfaces
  • Dependency Inversion Principle (DIP): High-level modules depend on abstractions

Usage Examples

Reading CSV Files

from unified_file_reader import read_file

data = read_file("employees.csv")
# Returns: [{"name": "John", "age": "30"}, {"name": "Jane", "age": "28"}]

for row in data:
    print(f"{row['name']}: {row['age']}")

Reading JSON Files

config = read_file("config.json")
# Returns: {"database": {"host": "localhost", "port": 5432}}

print(config["database"]["host"])

Reading Text Files

content = read_file("document.txt")
# Returns: "This is the file content..."

print(content)

Reading Excel Files

data = read_file("report.xlsx")
# Returns: [{"Quarter": "Q1", "Revenue": 100000}, ...]

for row in data:
    print(f"{row['Quarter']}: ${row['Revenue']}")

Reading PDF Files

text = read_file("document.pdf")
# Returns: "Page 1 content...\nPage 2 content..."

print(text)

Reading DOCX Files

text = read_file("report.docx")
# Returns: "Paragraph 1...\nParagraph 2..."

print(text)

Error Handling

from unified_file_reader import read_file
from unified_file_reader.exceptions import UnsupportedFormatError, ReaderError

try:
    data = read_file("file.xyz")
except UnsupportedFormatError as e:
    print(f"Format not supported: {e}")
except FileNotFoundError as e:
    print(f"File not found: {e}")
except ReaderError as e:
    print(f"Reading error: {e}")

Extending with New Readers

To add support for a new file format:

  1. Create a new reader class in unified_file_reader/readers/:
from unified_file_reader.interfaces.base_reader import BaseReader
from unified_file_reader.utils.file_utils import ensure_file_exists

class YAMLReader(BaseReader):
    supported_extensions = [".yaml", ".yml"]

    def can_read(self, extension: str) -> bool:
        return extension in self.supported_extensions

    def read(self, path: str):
        ensure_file_exists(path)
        import yaml
        with open(path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
  1. Register it in unified_file_reader/registry.py:
from unified_file_reader.readers.yaml_reader import YAMLReader

readers = [
    # ... existing readers ...
    YAMLReader(),
]
  1. Add tests in tests/test_yaml_reader.py

  2. Update supported_formats.py with metadata

That's it! No changes needed to the core API.

Testing

Run the test suite:

pytest

With coverage:

pytest --cov=unified_file_reader

Run specific tests:

pytest tests/test_api.py -v

Development

Install development dependencies:

pip install -e ".[dev]"

Format code:

black unified_file_reader tests
isort unified_file_reader tests

Type checking:

mypy unified_file_reader

Linting:

flake8 unified_file_reader tests

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License - see LICENSE file for details

Changelog

v0.1.0 (Initial Release)

  • Initial release with support for CSV, JSON, TXT, XLSX, PDF, DOCX
  • Clean Architecture implementation
  • Full test coverage
  • PyPI packaging

Support

For issues, questions, or suggestions, please open an issue on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

unified_file_reader-0.1.1.tar.gz (19.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

unified_file_reader-0.1.1-py3-none-any.whl (16.2 kB view details)

Uploaded Python 3

File details

Details for the file unified_file_reader-0.1.1.tar.gz.

File metadata

  • Download URL: unified_file_reader-0.1.1.tar.gz
  • Upload date:
  • Size: 19.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.8.10

File hashes

Hashes for unified_file_reader-0.1.1.tar.gz
Algorithm Hash digest
SHA256 493d7c1d4000b8cf7831634e24a4fa44e0fb238f380c59790df6996cf34c4dd6
MD5 d23d6a3f7d39f9552a68f16db3566e40
BLAKE2b-256 ca742decc41fafa9da8ca76a4f0a26654c34ae4033f8eb7e1f09d5341a20bfad

See more details on using hashes here.

File details

Details for the file unified_file_reader-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for unified_file_reader-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9aec379a00101f43b455a11fdc923fd267df1c2aeaebc20cd6dac5046ddc04a4
MD5 b544d6df33b96c4776c9d423c44f0439
BLAKE2b-256 ab99dda829ed0053f7b4047a44a62665f0fdb0b8fb728fcf5bf6bf226b3c4c35

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page