0
# Temporary File Operations
1
2
Async interface to Python's tempfile module, providing temporary files and directories with automatic cleanup. These functions create temporary storage that's automatically cleaned up when the context manager exits.
3
4
## Capabilities
5
6
### Named Temporary Files
7
8
Creates a temporary file with a visible name in the filesystem. The file can be opened by other processes using its name.
9
10
```python { .api }
11
def NamedTemporaryFile(
12
mode: str = "w+b",
13
buffering: int = -1,
14
encoding: str = None,
15
newline: str = None,
16
suffix: str = None,
17
prefix: str = None,
18
dir: str = None,
19
delete: bool = True,
20
delete_on_close: bool = True, # Python 3.12+ only
21
*,
22
loop = None,
23
executor = None
24
) -> AiofilesContextManager:
25
"""
26
Create async named temporary file.
27
28
Parameters:
29
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
30
- buffering: Buffer size (-1 for default)
31
- encoding: Text encoding (for text modes)
32
- newline: Newline handling
33
- suffix: Filename suffix (e.g., '.txt')
34
- prefix: Filename prefix
35
- dir: Directory to create file in (defaults to temp directory)
36
- delete: Whether to delete file when closed
37
- delete_on_close: Whether to delete file when closed (Python 3.12+)
38
- loop: Event loop to use
39
- executor: Thread pool executor to use
40
41
Returns:
42
AiofilesContextManager yielding async file object with .name attribute
43
"""
44
```
45
46
**Usage Example:**
47
48
```python
49
import aiofiles.tempfile
50
51
# Create and use named temporary file
52
async with aiofiles.tempfile.NamedTemporaryFile(mode='w+', suffix='.txt') as f:
53
# File has a name accessible to other processes
54
print(f"Temp file name: {f.name}")
55
56
await f.write("Temporary data")
57
await f.seek(0)
58
content = await f.read()
59
print(content)
60
# File is automatically deleted when context exits (if delete=True)
61
62
# Keep temporary file after closing
63
async with aiofiles.tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
64
await f.write("Data to keep")
65
temp_filename = f.name
66
print(f"File saved as: {temp_filename}")
67
```
68
69
### Unnamed Temporary Files
70
71
Creates a temporary file without a visible name in the filesystem. More secure as other processes cannot access it.
72
73
```python { .api }
74
def TemporaryFile(
75
mode: str = "w+b",
76
buffering: int = -1,
77
encoding: str = None,
78
newline: str = None,
79
suffix: str = None,
80
prefix: str = None,
81
dir: str = None,
82
*,
83
loop = None,
84
executor = None
85
) -> AiofilesContextManager:
86
"""
87
Create async unnamed temporary file.
88
89
Parameters:
90
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
91
- buffering: Buffer size (-1 for default)
92
- encoding: Text encoding (for text modes)
93
- newline: Newline handling
94
- suffix: Filename suffix (e.g., '.txt')
95
- prefix: Filename prefix
96
- dir: Directory to create file in (defaults to temp directory)
97
- loop: Event loop to use
98
- executor: Thread pool executor to use
99
100
Returns:
101
AiofilesContextManager yielding async file object without accessible name
102
"""
103
```
104
105
**Usage Example:**
106
107
```python
108
import aiofiles.tempfile
109
110
# Create unnamed temporary file
111
async with aiofiles.tempfile.TemporaryFile(mode='w+') as f:
112
await f.write("Temporary data")
113
await f.seek(0)
114
content = await f.read()
115
print(content)
116
# File is automatically deleted when context exits
117
```
118
119
### Spooled Temporary Files
120
121
Creates a temporary file that initially exists in memory and is moved to disk only when it exceeds a specified size threshold.
122
123
```python { .api }
124
def SpooledTemporaryFile(
125
max_size: int = 0,
126
mode: str = "w+b",
127
buffering: int = -1,
128
encoding: str = None,
129
newline: str = None,
130
suffix: str = None,
131
prefix: str = None,
132
dir: str = None,
133
*,
134
loop = None,
135
executor = None
136
) -> AiofilesContextManager:
137
"""
138
Create async spooled temporary file.
139
140
Parameters:
141
- max_size: Maximum size in memory before moving to disk (0 = always disk)
142
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
143
- buffering: Buffer size (-1 for default)
144
- encoding: Text encoding (for text modes)
145
- newline: Newline handling
146
- suffix: Filename suffix when moved to disk
147
- prefix: Filename prefix when moved to disk
148
- dir: Directory for disk file (defaults to temp directory)
149
- loop: Event loop to use
150
- executor: Thread pool executor to use
151
152
Returns:
153
AiofilesContextManager yielding async spooled file object
154
"""
155
```
156
157
**Usage Example:**
158
159
```python
160
import aiofiles.tempfile
161
162
# Small data stays in memory, large data goes to disk
163
async with aiofiles.tempfile.SpooledTemporaryFile(max_size=1024) as f:
164
# Small write - stays in memory
165
await f.write("Small data")
166
167
# Large write - automatically spools to disk
168
await f.write("x" * 2000)
169
170
# Check if rolled to disk
171
if hasattr(f._file, '_rolled') and f._file._rolled:
172
print("File was spooled to disk")
173
174
await f.seek(0)
175
content = await f.read()
176
```
177
178
### Temporary Directories
179
180
Creates a temporary directory that is automatically cleaned up when the context manager exits.
181
182
```python { .api }
183
def TemporaryDirectory(
184
suffix: str = None,
185
prefix: str = None,
186
dir: str = None,
187
*,
188
loop = None,
189
executor = None
190
) -> AiofilesContextManagerTempDir:
191
"""
192
Create async temporary directory.
193
194
Parameters:
195
- suffix: Directory name suffix
196
- prefix: Directory name prefix
197
- dir: Parent directory (defaults to system temp directory)
198
- loop: Event loop to use
199
- executor: Thread pool executor to use
200
201
Returns:
202
AiofilesContextManagerTempDir yielding directory path string
203
"""
204
```
205
206
**Usage Example:**
207
208
```python
209
import aiofiles.tempfile
210
import aiofiles.os
211
212
# Create temporary directory
213
async with aiofiles.tempfile.TemporaryDirectory() as temp_dir:
214
print(f"Temp directory: {temp_dir}")
215
216
# Create files in temporary directory
217
file_path = f"{temp_dir}/data.txt"
218
async with aiofiles.open(file_path, 'w') as f:
219
await f.write("Temporary file data")
220
221
# List directory contents
222
files = await aiofiles.os.listdir(temp_dir)
223
print(f"Files in temp dir: {files}")
224
225
# Directory and all contents are automatically deleted
226
```
227
228
## Spooled File Interface
229
230
Spooled temporary files provide additional methods for managing the memory/disk transition:
231
232
```python { .api }
233
async def rollover():
234
"""Force the file to roll over to disk."""
235
236
def fileno() -> int:
237
"""Get file descriptor (only available after rollover to disk)."""
238
239
# Properties
240
_rolled: bool # Whether file has been moved to disk
241
```
242
243
**Usage Example:**
244
245
```python
246
import aiofiles.tempfile
247
248
async with aiofiles.tempfile.SpooledTemporaryFile(max_size=1024) as f:
249
await f.write("Small data")
250
251
# Force rollover to disk
252
await f.rollover()
253
254
# Now file descriptor is available
255
fd = f.fileno()
256
print(f"File descriptor: {fd}")
257
```
258
259
## Error Handling
260
261
Temporary file operations may raise:
262
263
- `OSError`: General OS-level errors
264
- `PermissionError`: Insufficient permissions for temp directory
265
- `FileExistsError`: Conflict in temporary file creation
266
- `ValueError`: Invalid arguments
267
268
**Usage Example:**
269
270
```python
271
import aiofiles.tempfile
272
273
try:
274
async with aiofiles.tempfile.NamedTemporaryFile() as f:
275
await f.write("data")
276
except PermissionError:
277
print("Cannot create temporary file - permission denied")
278
except OSError as e:
279
print(f"OS error creating temporary file: {e}")
280
```