files.py¶
File operation utilities for NodeWeaver.
This module provides utilities for reading and writing files, with a focus on JSON handling and validation. It includes functions for safe file operations with proper error handling and user feedback.
read_json(path)
¶
Read and validate a JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[str, Path]
|
Path to JSON file as string or Path object |
required |
Returns:
Type | Description |
---|---|
Optional[Dict[str, Any]]
|
Dictionary of JSON contents if valid, None if invalid |
Notes
- Validates file existence and .json extension
- Checks for non-empty content
- Prints warning messages for invalid files
Example
data = read_json("config/settings.json") if data: ... print("Settings loaded")
Since: 1.0.0
Source code in utils/files.py
write_json(path, data, indent=2, create_dirs=True, overwrite=False)
¶
Write a dictionary to a JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[str, Path]
|
Path to JSON file as string or Path object |
required |
data
|
Dict[str, Any]
|
Dictionary to write to file |
required |
indent
|
int
|
Number of spaces for JSON indentation |
2
|
create_dirs
|
bool
|
Whether to create parent directories if they don't exist |
True
|
overwrite
|
bool
|
Whether to overwrite existing file without prompting |
False
|
Returns:
Type | Description |
---|---|
bool
|
True if write successful, False otherwise |
Examples:
Notes
- Creates parent directories if create_dirs=True
- Prompts for confirmation before overwriting unless overwrite=True
- Uses consistent indentation for readability
Since: 1.0.0