0
# Core File Operations
1
2
Basic file opening, reading, writing, and access to standard streams. These operations form the foundation of aiofiles functionality and provide async versions of Python's built-in file operations.
3
4
## Capabilities
5
6
### File Opening
7
8
Opens files asynchronously with the same signature as Python's built-in `open()` function, but returns an async context manager.
9
10
```python { .api }
11
def open(
12
file,
13
mode: str = "r",
14
buffering: int = -1,
15
encoding: str = None,
16
errors: str = None,
17
newline: str = None,
18
closefd: bool = True,
19
opener = None,
20
*,
21
loop = None,
22
executor = None
23
) -> AiofilesContextManager:
24
"""
25
Open file and return async context manager.
26
27
Parameters:
28
- file: File path or file descriptor to open
29
- mode: File open mode ('r', 'w', 'a', 'rb', 'wb', etc.)
30
- buffering: Buffer size (-1 for default, 0 for unbuffered, >0 for buffer size)
31
- encoding: Text encoding (for text mode files)
32
- errors: How to handle encoding errors ('strict', 'ignore', 'replace')
33
- newline: How to handle newlines (None, '', '\n', '\r', '\r\n')
34
- closefd: Whether to close file descriptor when file is closed
35
- opener: Custom opener function
36
- loop: Event loop to use (defaults to current running loop)
37
- executor: Thread pool executor to use (defaults to loop's default executor)
38
39
Returns:
40
AiofilesContextManager that yields async file object when awaited
41
"""
42
```
43
44
**Usage Example:**
45
46
```python
47
import aiofiles
48
49
# Text file operations
50
async with aiofiles.open('data.txt', mode='r') as f:
51
content = await f.read()
52
53
async with aiofiles.open('output.txt', mode='w', encoding='utf-8') as f:
54
await f.write('Hello, world!')
55
56
# Binary file operations
57
async with aiofiles.open('image.jpg', mode='rb') as f:
58
data = await f.read()
59
60
async with aiofiles.open('data.bin', mode='wb') as f:
61
await f.write(b'Binary data')
62
```
63
64
### Standard Stream Access
65
66
Async access to standard input, output, and error streams including both text and binary interfaces.
67
68
```python { .api }
69
stdin: AsyncTextIndirectIOWrapper
70
"""Async text interface to sys.stdin"""
71
72
stdout: AsyncTextIndirectIOWrapper
73
"""Async text interface to sys.stdout"""
74
75
stderr: AsyncTextIndirectIOWrapper
76
"""Async text interface to sys.stderr"""
77
78
stdin_bytes: AsyncIndirectBufferedIOBase
79
"""Async binary interface to sys.stdin.buffer"""
80
81
stdout_bytes: AsyncIndirectBufferedIOBase
82
"""Async binary interface to sys.stdout.buffer"""
83
84
stderr_bytes: AsyncIndirectBufferedIOBase
85
"""Async binary interface to sys.stderr.buffer"""
86
```
87
88
**Usage Example:**
89
90
```python
91
import aiofiles
92
93
# Reading from stdin
94
line = await aiofiles.stdin.readline()
95
print(f"You entered: {line.strip()}")
96
97
# Writing to stdout
98
await aiofiles.stdout.write("Hello from async stdout!\n")
99
await aiofiles.stdout.flush()
100
101
# Writing to stderr
102
await aiofiles.stderr.write("Error message\n")
103
104
# Binary operations
105
binary_data = await aiofiles.stdin_bytes.read(1024)
106
await aiofiles.stdout_bytes.write(b"Binary output\n")
107
```
108
109
## Async File Object Interface
110
111
All async file objects returned by `aiofiles.open()` provide the following interface:
112
113
### Reading Methods
114
115
```python { .api }
116
async def read(size: int = -1):
117
"""Read up to size bytes. If size is -1, read entire file."""
118
119
async def read1(size: int = -1):
120
"""Read up to size bytes using single system call (binary files only)."""
121
122
async def readall():
123
"""Read entire file (binary files only)."""
124
125
async def readinto(b):
126
"""Read into existing buffer (binary files only)."""
127
128
async def readline(size: int = -1):
129
"""Read one line up to size characters."""
130
131
async def readlines(hint: int = -1):
132
"""Read lines into list, with optional size hint."""
133
```
134
135
### Writing Methods
136
137
```python { .api }
138
async def write(data):
139
"""Write data to file. Returns number of characters/bytes written."""
140
141
async def writelines(lines):
142
"""Write list of lines to file."""
143
144
async def flush():
145
"""Flush write buffers to disk."""
146
```
147
148
### File Position and Information
149
150
```python { .api }
151
async def seek(offset: int, whence: int = 0):
152
"""Seek to position. whence: 0=start, 1=current, 2=end."""
153
154
async def tell() -> int:
155
"""Get current file position."""
156
157
async def truncate(size: int = None):
158
"""Truncate file to size bytes (current position if None)."""
159
160
async def close():
161
"""Close the file."""
162
```
163
164
### File Properties and Capabilities
165
166
```python { .api }
167
async def seekable() -> bool:
168
"""Return whether file supports seeking."""
169
170
async def readable() -> bool:
171
"""Return whether file supports reading."""
172
173
async def writable() -> bool:
174
"""Return whether file supports writing."""
175
176
async def isatty() -> bool:
177
"""Return whether file is a TTY device."""
178
179
def fileno() -> int:
180
"""Return file descriptor number."""
181
182
# Properties (synchronous access)
183
closed: bool # Whether file is closed
184
name: str # File name
185
mode: str # File mode
186
encoding: str # Text encoding (text files only)
187
errors: str # Error handling mode (text files only)
188
newlines: str # Newline handling (text files only)
189
```
190
191
### Async Iteration
192
193
All async file objects support async iteration for line-by-line reading:
194
195
```python
196
async with aiofiles.open('data.txt') as f:
197
async for line in f:
198
print(line.strip())
199
```
200
201
## Error Handling
202
203
File operations may raise standard Python I/O exceptions:
204
205
- `FileNotFoundError`: File does not exist
206
- `PermissionError`: Insufficient permissions
207
- `IsADirectoryError`: Expected file but path is directory
208
- `OSError`: General OS-level errors
209
- `UnicodeError`: Text encoding/decoding errors
210
- `ValueError`: Invalid arguments (e.g., invalid mode)
211
212
**Usage Example:**
213
214
```python
215
import aiofiles
216
217
try:
218
async with aiofiles.open('nonexistent.txt', 'r') as f:
219
content = await f.read()
220
except FileNotFoundError:
221
print("File not found")
222
except PermissionError:
223
print("Permission denied")
224
except OSError as e:
225
print(f"OS error: {e}")
226
```