0
# High-Level Filesystem Interface
1
2
The LittleFS class provides a Python-like filesystem interface with automatic mounting, familiar file I/O operations, and comprehensive error handling. This high-level API handles the complexity of the underlying LittleFS C library while providing intuitive Python semantics.
3
4
## Capabilities
5
6
### LittleFS Class
7
8
Main filesystem interface that provides Python-like file and directory operations with automatic configuration and error handling.
9
10
```python { .api }
11
class LittleFS:
12
def __init__(self, context=None, mount=True, **kwargs) -> None:
13
"""
14
Initialize LittleFS filesystem.
15
16
Parameters:
17
- context: UserContext, storage backend (defaults to memory buffer)
18
- mount: bool, automatically mount after creation (default True)
19
- block_size: int, block size in bytes (default depends on context)
20
- block_count: int, number of blocks (default depends on context)
21
- name_max: int, maximum filename length (default 255)
22
- **kwargs: additional LFSConfig parameters
23
"""
24
```
25
26
### Filesystem Management
27
28
Core filesystem operations for formatting, mounting, and maintenance.
29
30
```python { .api }
31
def format(self) -> int:
32
"""
33
Format the underlying buffer.
34
35
Returns:
36
int: 0 on success
37
38
Raises:
39
LittleFSError: If block_count is 0 or formatting fails
40
"""
41
42
def mount(self) -> int:
43
"""
44
Mount the underlying buffer.
45
46
Returns:
47
int: 0 on success
48
49
Raises:
50
LittleFSError: If mounting fails
51
"""
52
53
def unmount(self) -> int:
54
"""
55
Unmount the underlying buffer.
56
57
Returns:
58
int: 0 on success
59
"""
60
61
def fs_mkconsistent(self) -> int:
62
"""
63
Attempt to make the filesystem consistent and ready for writing.
64
65
Returns:
66
int: 0 on success
67
"""
68
69
def fs_grow(self, block_count: int) -> int:
70
"""
71
Grow filesystem to new size. WARNING: does not modify underlying context.
72
73
Parameters:
74
- block_count: int, new block count (must be >= current block_count)
75
76
Returns:
77
int: 0 on success
78
79
Raises:
80
ValueError: If block_count is smaller than current size
81
"""
82
83
def fs_stat(self) -> LFSFSStat:
84
"""
85
Get filesystem status information.
86
87
Returns:
88
LFSFSStat: Filesystem statistics
89
"""
90
91
def fs_gc(self):
92
"""
93
Perform garbage collection on the filesystem.
94
95
Returns:
96
int: 0 on success
97
"""
98
```
99
100
### File Operations
101
102
High-level file I/O operations using Python's familiar file interface.
103
104
```python { .api }
105
def open(self, fname: str, mode="r", buffering: int = -1, encoding: str = None,
106
errors: str = None, newline: str = None):
107
"""
108
Open a file with Python-like semantics.
109
110
Parameters:
111
- fname: str, path to file
112
- mode: str, file mode ('r', 'w', 'a', 'x', 'b', 't', '+')
113
- buffering: int, buffering policy (-1 for default, 0 for unbuffered in binary mode)
114
- encoding: str, text encoding (text mode only)
115
- errors: str, error handling (text mode only)
116
- newline: str, newline handling (text mode only)
117
118
Returns:
119
IO object (TextIOWrapper, BufferedReader, BufferedWriter, or FileHandle)
120
121
Raises:
122
FileNotFoundError: File not found
123
IsADirectoryError: Path is a directory
124
FileExistsError: File exists in exclusive create mode
125
ValueError: Invalid mode string
126
"""
127
```
128
129
### Directory Operations
130
131
Directory creation, listing, and management with Python os module semantics.
132
133
```python { .api }
134
def listdir(self, path=".") -> List[str]:
135
"""
136
List directory contents.
137
138
Parameters:
139
- path: str, directory path (default current directory)
140
141
Returns:
142
List[str]: List of filenames and directory names
143
"""
144
145
def mkdir(self, path: str) -> int:
146
"""
147
Create a directory.
148
149
Parameters:
150
- path: str, directory path to create
151
152
Returns:
153
int: 0 on success
154
155
Raises:
156
FileExistsError: Directory already exists
157
"""
158
159
def makedirs(self, name: str, exist_ok=False):
160
"""
161
Create directories recursively.
162
163
Parameters:
164
- name: str, directory path to create
165
- exist_ok: bool, don't raise error if final directory exists
166
167
Raises:
168
FileExistsError: Directory exists and exist_ok=False
169
"""
170
171
def scandir(self, path="."):
172
"""
173
Scan directory and yield LFSStat objects.
174
175
Parameters:
176
- path: str, directory path to scan
177
178
Yields:
179
LFSStat: File/directory status for each entry
180
"""
181
182
def rmdir(self, path: str) -> int:
183
"""
184
Remove a directory (alias for remove).
185
186
Parameters:
187
- path: str, directory path to remove
188
189
Returns:
190
int: 0 on success
191
"""
192
193
def removedirs(self, name):
194
"""
195
Remove directories recursively up the tree.
196
197
Parameters:
198
- name: str, directory path to start removal
199
"""
200
```
201
202
### Path Operations
203
204
File and directory manipulation operations.
205
206
```python { .api }
207
def remove(self, path: str, recursive: bool = False) -> None:
208
"""
209
Remove a file or directory.
210
211
Parameters:
212
- path: str, path to remove
213
- recursive: bool, recursively remove directory contents
214
215
Raises:
216
FileNotFoundError: Path does not exist
217
"""
218
219
def rename(self, src: str, dst: str) -> int:
220
"""
221
Rename or move a file or directory.
222
223
Parameters:
224
- src: str, current path
225
- dst: str, new path
226
227
Returns:
228
int: 0 on success
229
"""
230
231
def stat(self, path: str) -> LFSStat:
232
"""
233
Get file or directory status.
234
235
Parameters:
236
- path: str, path to examine
237
238
Returns:
239
LFSStat: Status information (type, size, name)
240
"""
241
242
def unlink(self, path: str) -> int:
243
"""
244
Remove a file (alias for remove).
245
246
Parameters:
247
- path: str, file path to remove
248
249
Returns:
250
int: 0 on success
251
"""
252
```
253
254
### Extended Attributes
255
256
Extended attribute operations for storing metadata.
257
258
```python { .api }
259
def getattr(self, path: str, typ: Union[str, bytes, int]) -> bytes:
260
"""
261
Get extended attribute value.
262
263
Parameters:
264
- path: str, file or directory path
265
- typ: str/bytes/int, attribute type (0-255)
266
267
Returns:
268
bytes: Attribute data
269
"""
270
271
def setattr(self, path: str, typ: Union[str, bytes, int], data: bytes) -> None:
272
"""
273
Set extended attribute value.
274
275
Parameters:
276
- path: str, file or directory path
277
- typ: str/bytes/int, attribute type (0-255)
278
- data: bytes, attribute data to store
279
"""
280
281
def removeattr(self, path: str, typ: Union[str, bytes, int]) -> None:
282
"""
283
Remove extended attribute.
284
285
Parameters:
286
- path: str, file or directory path
287
- typ: str/bytes/int, attribute type (0-255)
288
"""
289
```
290
291
### Tree Walking
292
293
Directory tree traversal utilities.
294
295
```python { .api }
296
def walk(self, top: str):
297
"""
298
Generate file names in directory tree by walking top-down.
299
300
Parameters:
301
- top: str, root directory to start walking
302
303
Yields:
304
Tuple[str, List[str], List[str]]: (root, dirs, files) for each directory
305
"""
306
```
307
308
### Properties
309
310
Filesystem information and context access.
311
312
```python { .api }
313
@property
314
def block_count(self) -> int:
315
"""Total number of blocks in filesystem."""
316
317
@property
318
def used_block_count(self) -> int:
319
"""Number of blocks currently in use."""
320
321
@property
322
def context(self) -> UserContext:
323
"""User context (storage backend) of the filesystem."""
324
```
325
326
## Usage Examples
327
328
### Creating and Using a Filesystem
329
330
```python
331
from littlefs import LittleFS
332
333
# Create 1MB filesystem
334
fs = LittleFS(block_size=512, block_count=2048)
335
336
# Write configuration file
337
with fs.open('config.json', 'w') as f:
338
f.write('{"debug": true, "port": 8080}')
339
340
# Create directory structure
341
fs.makedirs('logs/app', exist_ok=True)
342
fs.makedirs('data/cache', exist_ok=True)
343
344
# Write log files
345
for i in range(3):
346
with fs.open(f'logs/app/log_{i}.txt', 'w') as f:
347
f.write(f'Log entry {i}\\n')
348
349
# List all files
350
for root, dirs, files in fs.walk('/'):
351
for file in files:
352
path = f"{root.rstrip('/')}/{file}"
353
stat_info = fs.stat(path)
354
print(f"{path}: {stat_info.size} bytes")
355
```
356
357
### Working with Extended Attributes
358
359
```python
360
# Set custom metadata
361
fs.setattr('config.json', 'version', b'1.2.0')
362
fs.setattr('config.json', 'created', b'2024-01-15')
363
364
# Read metadata
365
version = fs.getattr('config.json', 'version')
366
created = fs.getattr('config.json', 'created')
367
368
print(f"Version: {version.decode()}")
369
print(f"Created: {created.decode()}")
370
```
371
372
### Filesystem Maintenance
373
374
```python
375
# Check filesystem status
376
fs_stat = fs.fs_stat()
377
print(f"Block size: {fs_stat.block_size}")
378
print(f"Used blocks: {fs.used_block_count}/{fs.block_count}")
379
380
# Perform garbage collection if needed
381
if fs.used_block_count > fs.block_count * 0.8:
382
fs.fs_gc()
383
384
# Grow filesystem if needed
385
if fs.used_block_count > fs.block_count * 0.9:
386
fs.fs_grow(fs.block_count * 2)
387
```