Metadata-Version: 2.4
Name: withopen_lite
Version: 1.5.0
Summary: A structure-aware and data type text file manager for Python that enforces type safety, 1D/2D consistency, and automatic backups.
Author: henry
Author-email: osas2henry@gmail.com
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: License :: OSI Approved :: MIT License
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: requires-python
Dynamic: summary

---

# 🪖 withopen lite

**Your code's .txt sidekick**

A zero dependency, structure aware, and type safe text file manager for Python.
It reads any `.txt` file in your working directory, validates its structure, and replaces repetitive file I/O logic with clean one liners.

---

## 🎯 Why withopen lite

After writing hundreds of:

```python
with open(file) as f:
```

blocks and rebuilding the same read, write, or append logic, I wanted something simpler.

withopen lite is the minimalist edition:

* Skips folders and tags
* Focuses purely on data integrity and consistency

Perfect for:

* Small automation scripts
* CLI tools
* Local bot storage
* Quick data caching
* Learning structured file management

---

## ⚡ Key Features

| Feature                     | Description                                                       |
| --------------------------- | ----------------------------------------------------------------- |
| Type safe validation        | Enforces consistent data types across rows and columns            |
| 1D and 2D structure locking | Detects and enforces whether your file is a list or list of lists |
| Auto backup                 | Every write automatically mirrors to (file)_backup.txt            |
| Zero dependencies           | Uses only Python built ins (os and ast)                           |
| Simple API                  | w(), a(), r() only                                                |
| No tags or folders          | Reads any .txt in your working directory                          |
| Readable format             | Uses literal Python syntax (['a', 'b'] not JSON)                  |
| Smart select indexing       | Select columns or elements directly from read data                |

---

## 🧩 Core Functions

### Understanding key parameters (explained once)

* `is2d`: Determines if the file is 1D (flat list) or 2D (list of lists).

  * Use `is2d=False` for a 1D list on the first write.
  * 2D lists are detected automatically (`is2d=None`) for beginners.

* `validate`: Checks that data types and structure are consistent.

  * Default is True, so beginners can skip it.
  * Set `validate=False` if you want to skip type and structure checks.

---

### Write: `w(txt_name, write_list, is2d=None, validate=True)`

Overwrite or create a new file. Locks file shape on first write.

```python
import withopen_lite as f

# Explicitly validating
f.w("tasks", [["Name", "Status"], ["Alice", "Done"]], validate=True)

# Using default behavior (validate=True)
f.w("tasks", [["Name", "Status"], ["Alice", "Done"]])

# 1D list example
f.w("fruits", ["apple", "banana", "pear"], is2d=False)
```

---

### Append: `a(txt_name, append_list, is2d=None, validate=True)`

Append data safely, enforcing structure and type consistency.

```python
# 2D append
f.a("tasks", [["Bob", "Pending"]])

# 1D append
f.a("fruits", ["orange"], is2d=False)

# Wrong example
f.a("tasks", ["Charlie", "Done"])
# Registers as flat list instead of 2D
```

---

### Read: `r(txt_name, index=None, set_new=None, display=True, validate=True)`

Read structured data, now with smart selection indexing.

```python
# Normal read
data = f.r("tasks")
print(data)

# Select a specific column (for example, names)
names = f.r("tasks", index=0)

# Select multiple columns
subset = f.r("tasks", index=[0, 2])

# Return default if file does not exist
data = f.r("missing_file", set_new=[["Header1", "Header2"]])
```

#### Parameters

| Parameter | Type                      | Default | Description                                     |
| --------- | ------------------------- | ------- | ----------------------------------------------- |
| txt_name  | str                       | none    | Base file name (with or without .txt extension) |
| index     | int, list, tuple, or None | None    | Select specific columns or elements directly    |
| set_new   | list or None              | []      | Default return if file is missing               |
| display   | bool                      | True    | Prints notice if file does not exist            |
| validate  | bool                      | True    | Checks structure and data types after reading   |

#### Behavior

* Reads file.txt first, then file_backup.txt as fallback.
* Returns set_new if neither exists.
* Integrates smart_select for column based selection on 2D data or element selection on 1D data.

#### Examples

```python
# tasks.txt → [["Name", "Status"], ["Alice", "Done"], ["Bob", "Pending"]]

f.r("tasks", index=0)
# → ["Name", "Alice", "Bob"]

f.r("tasks", index=[0, 1])
# → [["Name", "Status"], ["Alice", "Done"], ["Bob", "Pending"]]
```

---

## 🧠 Smart Select: `smart_select(data, index)`

Select elements from a 1D or 2D list based on a given index or indexes.

This function powers the new index parameter in r().

```python
from withopen_lite import smart_select

data_1d = ["apple", "banana", "cherry"]
print(smart_select(data_1d, 1))         # 'banana'
print(smart_select(data_1d, [0, 2]))    # ['apple', 'cherry']

data_2d = [
    ["Alice", 25, "Paris"],
    ["Bob", 30, "London"]
]
print(smart_select(data_2d, 0))         # ['Alice', 'Bob']
print(smart_select(data_2d, [0, 2]))    # [['Alice', 'Paris'], ['Bob', 'London']]
```

---

## 🔄 Using Loops Safely

```python
datas = [
    ["Alice", 25, "Paris"],
    ["Bob", 30, "London"]
]

# Correct append
for row in datas:
    f.a("people", [row])

# Correct write if starting fresh
for row in datas:
    f.w("people", [row])

# Wrong
for row in datas:
    f.a("people", row)
# Registers file as flat list instead of 2D
```

---

## 🔍 Type Safety

```python
f.w("scores", [["user", "score"], ["Alice", 10]])
f.a("scores", [["Bob", "12"]])
```

```
Data type mismatch detected!
Line 1, Column 2
 Expected  : int
 Found     : str (from value: '12')
```

---

## 🧰 Backup Behavior

* Every file automatically maintains a mirror backup: tasks_backup.txt
* Reads backup if main file fails or is empty

---

## ⚡ Quick Reference

| Function | Usage          | Notes                      |
| -------- | -------------- | -------------------------- |
| w        | Write new data | Overwrites existing file   |
| a        | Append data    | Must match shape           |
| r        | Read data      | Returns default if missing |

**index**
New in this version. Select columns or items directly from your data.

**is2d**
Needed for 1D flat lists. Optional for 2D lists.

**validate**
Checks that file structure and data types match. Default is True.

---

## 🧩 Internal Validation

### r_parameter_validation()

Ensures all parameters for r() are correctly typed.
Raises TypeError or IndexError for incorrect input.

---

## 📦 Installation

```bash
pip install withopen lite
```

---

## 🪖 Philosophy

Small tools should feel invisible.

withopen lite is not a database.
It is a confidence layer between your code and plain text.
No frameworks, no clutter, just reliable data I/O.

---

## 📄 License

MIT License © 2025
Created by [Henry]
Part of the withopen project family

---
