File support for asyncio applications providing async/await compatible file operations.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Creates a temporary file with a visible name in the filesystem. The file can be opened by other processes using its name.
def NamedTemporaryFile(
mode: str = "w+b",
buffering: int = -1,
encoding: str = None,
newline: str = None,
suffix: str = None,
prefix: str = None,
dir: str = None,
delete: bool = True,
delete_on_close: bool = True, # Python 3.12+ only
*,
loop = None,
executor = None
) -> AiofilesContextManager:
"""
Create async named temporary file.
Parameters:
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
- buffering: Buffer size (-1 for default)
- encoding: Text encoding (for text modes)
- newline: Newline handling
- suffix: Filename suffix (e.g., '.txt')
- prefix: Filename prefix
- dir: Directory to create file in (defaults to temp directory)
- delete: Whether to delete file when closed
- delete_on_close: Whether to delete file when closed (Python 3.12+)
- loop: Event loop to use
- executor: Thread pool executor to use
Returns:
AiofilesContextManager yielding async file object with .name attribute
"""Usage Example:
import aiofiles.tempfile
# Create and use named temporary file
async with aiofiles.tempfile.NamedTemporaryFile(mode='w+', suffix='.txt') as f:
# File has a name accessible to other processes
print(f"Temp file name: {f.name}")
await f.write("Temporary data")
await f.seek(0)
content = await f.read()
print(content)
# File is automatically deleted when context exits (if delete=True)
# Keep temporary file after closing
async with aiofiles.tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
await f.write("Data to keep")
temp_filename = f.name
print(f"File saved as: {temp_filename}")Creates a temporary file without a visible name in the filesystem. More secure as other processes cannot access it.
def TemporaryFile(
mode: str = "w+b",
buffering: int = -1,
encoding: str = None,
newline: str = None,
suffix: str = None,
prefix: str = None,
dir: str = None,
*,
loop = None,
executor = None
) -> AiofilesContextManager:
"""
Create async unnamed temporary file.
Parameters:
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
- buffering: Buffer size (-1 for default)
- encoding: Text encoding (for text modes)
- newline: Newline handling
- suffix: Filename suffix (e.g., '.txt')
- prefix: Filename prefix
- dir: Directory to create file in (defaults to temp directory)
- loop: Event loop to use
- executor: Thread pool executor to use
Returns:
AiofilesContextManager yielding async file object without accessible name
"""Usage Example:
import aiofiles.tempfile
# Create unnamed temporary file
async with aiofiles.tempfile.TemporaryFile(mode='w+') as f:
await f.write("Temporary data")
await f.seek(0)
content = await f.read()
print(content)
# File is automatically deleted when context exitsCreates a temporary file that initially exists in memory and is moved to disk only when it exceeds a specified size threshold.
def SpooledTemporaryFile(
max_size: int = 0,
mode: str = "w+b",
buffering: int = -1,
encoding: str = None,
newline: str = None,
suffix: str = None,
prefix: str = None,
dir: str = None,
*,
loop = None,
executor = None
) -> AiofilesContextManager:
"""
Create async spooled temporary file.
Parameters:
- max_size: Maximum size in memory before moving to disk (0 = always disk)
- mode: File mode ('w+b', 'w+', 'r+b', etc.)
- buffering: Buffer size (-1 for default)
- encoding: Text encoding (for text modes)
- newline: Newline handling
- suffix: Filename suffix when moved to disk
- prefix: Filename prefix when moved to disk
- dir: Directory for disk file (defaults to temp directory)
- loop: Event loop to use
- executor: Thread pool executor to use
Returns:
AiofilesContextManager yielding async spooled file object
"""Usage Example:
import aiofiles.tempfile
# Small data stays in memory, large data goes to disk
async with aiofiles.tempfile.SpooledTemporaryFile(max_size=1024) as f:
# Small write - stays in memory
await f.write("Small data")
# Large write - automatically spools to disk
await f.write("x" * 2000)
# Check if rolled to disk
if hasattr(f._file, '_rolled') and f._file._rolled:
print("File was spooled to disk")
await f.seek(0)
content = await f.read()Creates a temporary directory that is automatically cleaned up when the context manager exits.
def TemporaryDirectory(
suffix: str = None,
prefix: str = None,
dir: str = None,
*,
loop = None,
executor = None
) -> AiofilesContextManagerTempDir:
"""
Create async temporary directory.
Parameters:
- suffix: Directory name suffix
- prefix: Directory name prefix
- dir: Parent directory (defaults to system temp directory)
- loop: Event loop to use
- executor: Thread pool executor to use
Returns:
AiofilesContextManagerTempDir yielding directory path string
"""Usage Example:
import aiofiles.tempfile
import aiofiles.os
# Create temporary directory
async with aiofiles.tempfile.TemporaryDirectory() as temp_dir:
print(f"Temp directory: {temp_dir}")
# Create files in temporary directory
file_path = f"{temp_dir}/data.txt"
async with aiofiles.open(file_path, 'w') as f:
await f.write("Temporary file data")
# List directory contents
files = await aiofiles.os.listdir(temp_dir)
print(f"Files in temp dir: {files}")
# Directory and all contents are automatically deletedSpooled temporary files provide additional methods for managing the memory/disk transition:
async def rollover():
"""Force the file to roll over to disk."""
def fileno() -> int:
"""Get file descriptor (only available after rollover to disk)."""
# Properties
_rolled: bool # Whether file has been moved to diskUsage Example:
import aiofiles.tempfile
async with aiofiles.tempfile.SpooledTemporaryFile(max_size=1024) as f:
await f.write("Small data")
# Force rollover to disk
await f.rollover()
# Now file descriptor is available
fd = f.fileno()
print(f"File descriptor: {fd}")Temporary file operations may raise:
OSError: General OS-level errorsPermissionError: Insufficient permissions for temp directoryFileExistsError: Conflict in temporary file creationValueError: Invalid argumentsUsage Example:
import aiofiles.tempfile
try:
async with aiofiles.tempfile.NamedTemporaryFile() as f:
await f.write("data")
except PermissionError:
print("Cannot create temporary file - permission denied")
except OSError as e:
print(f"OS error creating temporary file: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-aiofiles