0
# OS File System Operations
1
2
Async versions of os module functions for file system operations like renaming, removing, creating directories, and getting file statistics. These functions delegate to thread pool executors to avoid blocking the asyncio event loop.
3
4
## Capabilities
5
6
### File Information
7
8
Get detailed information about files and directories including statistics, permissions, and metadata.
9
10
```python { .api }
11
async def stat(path: str, *, loop = None, executor = None):
12
"""
13
Get file or directory status.
14
15
Parameters:
16
- path: Path to file or directory
17
- loop: Event loop to use
18
- executor: Thread pool executor to use
19
20
Returns:
21
os.stat_result object with file information
22
"""
23
24
async def access(path: str, mode: int, *, loop = None, executor = None) -> bool:
25
"""
26
Check access permissions for path.
27
28
Parameters:
29
- path: Path to check
30
- mode: Access mode (os.F_OK, os.R_OK, os.W_OK, os.X_OK)
31
- loop: Event loop to use
32
- executor: Thread pool executor to use
33
34
Returns:
35
True if access is allowed, False otherwise
36
"""
37
```
38
39
**Usage Example:**
40
41
```python
42
import aiofiles.os
43
import os
44
45
# Get file statistics
46
stat_result = await aiofiles.os.stat('example.txt')
47
print(f"File size: {stat_result.st_size}")
48
print(f"Modified: {stat_result.st_mtime}")
49
print(f"Mode: {oct(stat_result.st_mode)}")
50
51
# Check file permissions
52
can_read = await aiofiles.os.access('example.txt', os.R_OK)
53
can_write = await aiofiles.os.access('example.txt', os.W_OK)
54
exists = await aiofiles.os.access('example.txt', os.F_OK)
55
```
56
57
### File Operations
58
59
Basic file operations including renaming, removing, and linking files.
60
61
```python { .api }
62
async def rename(src: str, dst: str, *, loop = None, executor = None):
63
"""
64
Rename file or directory from src to dst.
65
66
Parameters:
67
- src: Source path
68
- dst: Destination path
69
- loop: Event loop to use
70
- executor: Thread pool executor to use
71
"""
72
73
async def renames(old: str, new: str, *, loop = None, executor = None):
74
"""
75
Recursive rename with directory creation and cleanup.
76
77
Parameters:
78
- old: Old path
79
- new: New path (directories created as needed)
80
- loop: Event loop to use
81
- executor: Thread pool executor to use
82
"""
83
84
async def replace(src: str, dst: str, *, loop = None, executor = None):
85
"""
86
Replace dst with src, overwriting dst if it exists.
87
88
Parameters:
89
- src: Source file path
90
- dst: Destination file path
91
- loop: Event loop to use
92
- executor: Thread pool executor to use
93
"""
94
95
async def remove(path: str, *, loop = None, executor = None):
96
"""
97
Remove (delete) file.
98
99
Parameters:
100
- path: Path to file to remove
101
- loop: Event loop to use
102
- executor: Thread pool executor to use
103
"""
104
105
async def unlink(path: str, *, loop = None, executor = None):
106
"""
107
Remove (delete) file. Same as remove().
108
109
Parameters:
110
- path: Path to file to unlink
111
- loop: Event loop to use
112
- executor: Thread pool executor to use
113
"""
114
```
115
116
**Usage Example:**
117
118
```python
119
import aiofiles.os
120
121
# Rename file
122
await aiofiles.os.rename('old_name.txt', 'new_name.txt')
123
124
# Replace file (overwrites destination)
125
await aiofiles.os.replace('source.txt', 'destination.txt')
126
127
# Remove file
128
await aiofiles.os.remove('unwanted_file.txt')
129
130
# Recursive rename with directory creation
131
await aiofiles.os.renames('old/path/file.txt', 'new/path/file.txt')
132
```
133
134
### Directory Operations
135
136
Create, remove, and manage directories and their contents.
137
138
```python { .api }
139
async def mkdir(path: str, mode: int = 0o777, *, loop = None, executor = None):
140
"""
141
Create directory.
142
143
Parameters:
144
- path: Directory path to create
145
- mode: Directory permissions (default 0o777)
146
- loop: Event loop to use
147
- executor: Thread pool executor to use
148
"""
149
150
async def makedirs(name: str, mode: int = 0o777, exist_ok: bool = False, *, loop = None, executor = None):
151
"""
152
Create directories recursively.
153
154
Parameters:
155
- name: Directory path to create (including parents)
156
- mode: Directory permissions (default 0o777)
157
- exist_ok: Don't raise error if directory already exists
158
- loop: Event loop to use
159
- executor: Thread pool executor to use
160
"""
161
162
async def rmdir(path: str, *, loop = None, executor = None):
163
"""
164
Remove empty directory.
165
166
Parameters:
167
- path: Directory path to remove
168
- loop: Event loop to use
169
- executor: Thread pool executor to use
170
"""
171
172
async def removedirs(name: str, *, loop = None, executor = None):
173
"""
174
Remove directories recursively.
175
176
Parameters:
177
- name: Directory path to remove (including empty parents)
178
- loop: Event loop to use
179
- executor: Thread pool executor to use
180
"""
181
182
async def listdir(path: str = ".", *, loop = None, executor = None) -> list:
183
"""
184
List directory contents.
185
186
Parameters:
187
- path: Directory path to list (defaults to current directory)
188
- loop: Event loop to use
189
- executor: Thread pool executor to use
190
191
Returns:
192
List of filenames in directory
193
"""
194
195
async def scandir(path: str = ".", *, loop = None, executor = None):
196
"""
197
Return iterator of DirEntry objects for directory.
198
199
Parameters:
200
- path: Directory path to scan (defaults to current directory)
201
- loop: Event loop to use
202
- executor: Thread pool executor to use
203
204
Returns:
205
Iterator of os.DirEntry objects
206
"""
207
```
208
209
**Usage Example:**
210
211
```python
212
import aiofiles.os
213
214
# Create single directory
215
await aiofiles.os.mkdir('new_directory')
216
217
# Create directory hierarchy
218
await aiofiles.os.makedirs('path/to/nested/directory', exist_ok=True)
219
220
# List directory contents
221
files = await aiofiles.os.listdir('.')
222
print(f"Files in current directory: {files}")
223
224
# Scan directory with detailed info
225
async for entry in await aiofiles.os.scandir('.'):
226
if entry.is_file():
227
print(f"File: {entry.name}")
228
elif entry.is_dir():
229
print(f"Directory: {entry.name}")
230
231
# Remove empty directory
232
await aiofiles.os.rmdir('empty_directory')
233
234
# Remove directory tree
235
await aiofiles.os.removedirs('path/to/nested/directory')
236
```
237
238
### Symbolic Links
239
240
Create and manage symbolic links between files and directories.
241
242
```python { .api }
243
async def symlink(src: str, dst: str, target_is_directory: bool = False, *, loop = None, executor = None):
244
"""
245
Create symbolic link.
246
247
Parameters:
248
- src: Source path (link target)
249
- dst: Destination path (link location)
250
- target_is_directory: Whether target is directory (Windows only)
251
- loop: Event loop to use
252
- executor: Thread pool executor to use
253
"""
254
255
async def readlink(path: str, *, loop = None, executor = None) -> str:
256
"""
257
Read symbolic link target.
258
259
Parameters:
260
- path: Path to symbolic link
261
- loop: Event loop to use
262
- executor: Thread pool executor to use
263
264
Returns:
265
Target path of symbolic link
266
"""
267
```
268
269
**Usage Example:**
270
271
```python
272
import aiofiles.os
273
274
# Create symbolic link
275
await aiofiles.os.symlink('target_file.txt', 'link_to_file.txt')
276
277
# Read symbolic link
278
target = await aiofiles.os.readlink('link_to_file.txt')
279
print(f"Link points to: {target}")
280
281
# Create directory symbolic link (Windows)
282
await aiofiles.os.symlink('target_dir', 'link_to_dir', target_is_directory=True)
283
```
284
285
### System Information
286
287
Get current working directory and system-level file operations.
288
289
```python { .api }
290
async def getcwd(*, loop = None, executor = None) -> str:
291
"""
292
Get current working directory.
293
294
Parameters:
295
- loop: Event loop to use
296
- executor: Thread pool executor to use
297
298
Returns:
299
Current working directory path
300
"""
301
```
302
303
**Platform-specific functions (available if supported by OS):**
304
305
```python { .api }
306
async def link(src: str, dst: str, *, loop = None, executor = None):
307
"""Create hard link (Unix only)."""
308
309
async def sendfile(out_fd: int, in_fd: int, offset: int, count: int, *, loop = None, executor = None) -> int:
310
"""Send file data between file descriptors (Unix only)."""
311
312
async def statvfs(path: str, *, loop = None, executor = None):
313
"""Get filesystem statistics (Unix only)."""
314
```
315
316
**Usage Example:**
317
318
```python
319
import aiofiles.os
320
321
# Get current directory
322
cwd = await aiofiles.os.getcwd()
323
print(f"Current directory: {cwd}")
324
325
# Platform-specific operations (if available)
326
if hasattr(aiofiles.os, 'link'):
327
await aiofiles.os.link('source.txt', 'hardlink.txt')
328
329
if hasattr(aiofiles.os, 'statvfs'):
330
fs_stats = await aiofiles.os.statvfs('.')
331
print(f"Free space: {fs_stats.f_bavail * fs_stats.f_frsize}")
332
```
333
334
### Utility Functions
335
336
```python { .api }
337
def wrap(func):
338
"""
339
Wrap synchronous function to run in executor.
340
341
Parameters:
342
- func: Synchronous function to wrap
343
344
Returns:
345
Async function that runs the original function in thread pool executor
346
"""
347
```
348
349
This utility function can be used to create async versions of other os module functions not directly provided by aiofiles.
350
351
**Usage Example:**
352
353
```python
354
import aiofiles.os
355
import os
356
357
# Create async version of os.getcwdb (get current directory as bytes)
358
async_getcwdb = aiofiles.os.wrap(os.getcwdb)
359
current_dir_bytes = await async_getcwdb()
360
```
361
362
## Error Handling
363
364
OS operations may raise various exceptions:
365
366
- `FileNotFoundError`: File or directory not found
367
- `FileExistsError`: File or directory already exists
368
- `PermissionError`: Insufficient permissions
369
- `IsADirectoryError`: Expected file but got directory
370
- `NotADirectoryError`: Expected directory but got file
371
- `OSError`: General OS-level errors
372
- `NotImplementedError`: Operation not supported on platform
373
374
**Usage Example:**
375
376
```python
377
import aiofiles.os
378
379
try:
380
await aiofiles.os.remove('nonexistent.txt')
381
except FileNotFoundError:
382
print("File not found")
383
except PermissionError:
384
print("Permission denied")
385
except OSError as e:
386
print(f"OS error: {e}")
387
388
try:
389
await aiofiles.os.mkdir('existing_directory')
390
except FileExistsError:
391
print("Directory already exists")
392
```