0
# File Utilities
1
2
Utilities for working with files, directories, and different file formats. These utilities provide convenient functions for reading and writing JSON, YAML, and text files, as well as directory operations.
3
4
## Capabilities
5
6
### Directory Operations
7
8
List and filter files in directories with optional extension filtering.
9
10
```python { .api }
11
def list_files_with_extensions(
12
directory: str | Path,
13
extensions: list[str] | None = None
14
) -> list[Path]:
15
"""
16
List files in a directory with specified extensions or all files if no extensions are provided.
17
18
Args:
19
directory: The directory path as a string or Path object
20
extensions: A list of file extensions to filter. Default is None, which lists all files
21
22
Returns:
23
A list of Path objects for the matching files
24
25
Examples:
26
```python
27
import supervision as sv
28
29
# List all files in the directory
30
files = sv.list_files_with_extensions(directory='my_directory')
31
32
# List only files with '.txt' and '.md' extensions
33
files = sv.list_files_with_extensions(
34
directory='my_directory', extensions=['txt', 'md'])
35
```
36
"""
37
```
38
39
### JSON File Operations
40
41
Read and write JSON files with automatic numpy array serialization support.
42
43
```python { .api }
44
def read_json_file(file_path: str | Path) -> dict:
45
"""
46
Read and parse a JSON file.
47
48
Args:
49
file_path: Path to the JSON file
50
51
Returns:
52
Dictionary containing the parsed JSON data
53
"""
54
55
def save_json_file(data: dict, file_path: str | Path, indent: int = 3) -> None:
56
"""
57
Save dictionary data to a JSON file with numpy array support.
58
59
Args:
60
data: Dictionary data to save
61
file_path: Path where to save the JSON file
62
indent: JSON indentation for pretty printing
63
"""
64
65
class NumpyJsonEncoder(json.JSONEncoder):
66
"""
67
JSON encoder that handles numpy data types.
68
69
Automatically converts:
70
- numpy integers to Python int
71
- numpy floats to Python float
72
- numpy arrays to Python lists
73
"""
74
```
75
76
### YAML File Operations
77
78
Read and write YAML configuration files.
79
80
```python { .api }
81
def read_yaml_file(file_path: str | Path) -> dict:
82
"""
83
Read and parse a YAML file.
84
85
Args:
86
file_path: Path to the YAML file
87
88
Returns:
89
Dictionary containing the parsed YAML data
90
"""
91
92
def save_yaml_file(data: dict, file_path: str | Path) -> None:
93
"""
94
Save dictionary data to a YAML file.
95
96
Args:
97
data: Dictionary data to save
98
file_path: Path where to save the YAML file
99
"""
100
```
101
102
### Text File Operations
103
104
Basic text file reading and writing utilities.
105
106
```python { .api }
107
def read_txt_file(file_path: str | Path, skip_empty: bool = False) -> list[str]:
108
"""
109
Read a text file and return lines as a list.
110
111
Args:
112
file_path: Path to the text file
113
skip_empty: Whether to skip empty lines
114
115
Returns:
116
List of strings, one per line
117
"""
118
119
def save_text_file(lines: list[str], file_path: str | Path) -> None:
120
"""
121
Save a list of strings to a text file.
122
123
Args:
124
lines: List of strings to write
125
file_path: Path where to save the text file
126
"""
127
```
128
129
## Usage Examples
130
131
### Working with Project Configurations
132
133
```python
134
import supervision as sv
135
from pathlib import Path
136
137
# Read configuration from YAML
138
config = sv.read_yaml_file("config.yaml")
139
140
# Process some data
141
results = {
142
"detections": 150,
143
"confidence_scores": np.array([0.95, 0.87, 0.92]),
144
"processed_files": ["image1.jpg", "image2.jpg"]
145
}
146
147
# Save results as JSON (numpy arrays automatically handled)
148
sv.save_json_file(results, "results.json")
149
150
# List all image files in a directory
151
image_files = sv.list_files_with_extensions(
152
directory="./images",
153
extensions=["jpg", "jpeg", "png"]
154
)
155
156
print(f"Found {len(image_files)} image files")
157
```
158
159
### Data Export Workflows
160
161
```python
162
import supervision as sv
163
164
# Export detection results in multiple formats
165
detection_data = {
166
"model": "yolov8n",
167
"boxes": detections.xyxy.tolist(),
168
"scores": detections.confidence.tolist(),
169
"classes": detections.class_id.tolist()
170
}
171
172
# Save as JSON
173
sv.save_json_file(detection_data, "detections.json")
174
175
# Save as YAML for human readability
176
sv.save_yaml_file(detection_data, "detections.yaml")
177
178
# Export class names as text file
179
class_names = ["person", "car", "truck", "bus"]
180
sv.save_text_file(class_names, "classes.txt")
181
```