File
This class acts as a thin wrapper around a Python file object, providing additional metadata and utility methods for file handling. It supports efficient iteration through chunked reading and includes logic for determining file size across different storage backends. The class also implements a context manager interface and proxy methods to ensure compatibility with standard file-like objects.
Attributes
| Attribute | Type | Description |
|---|---|---|
| DEFAULT_CHUNK_SIZE | int = 65536 | The default number of bytes to read at once when yielding data from the file in chunks. |
Constructor
Signature
def File(
file: file-like object,
name: string = None
)
Parameters
| Name | Type | Description |
|---|---|---|
| file | file-like object | The underlying file-like object to be wrapped. |
| name | string = None | The name of the file. If not provided, it attempts to retrieve the name from the file object. |
Methods
size()
@classmethod
def size() - > integer
Calculates or retrieves the file size by checking the underlying file object, the filesystem, or by seeking to the end of the stream.
Returns
| Type | Description |
|---|---|
integer | The size of the file in bytes. |
chunks()
@classmethod
def chunks(
chunk_size: integer = None
) - > generator
Read the file and yield chunks of chunk_size bytes (defaults to File.DEFAULT_CHUNK_SIZE).
Parameters
| Name | Type | Description |
|---|---|---|
| chunk_size | integer = None | The number of bytes to read in each iteration; defaults to 64KB if not provided. |
Returns
| Type | Description |
|---|---|
generator | A generator yielding byte strings of the specified chunk size. |
multiple_chunks()
@classmethod
def multiple_chunks(
chunk_size: integer = None
) - > boolean
Return True if you can expect multiple chunks.
Parameters
| Name | Type | Description |
|---|---|---|
| chunk_size | integer = None | The size threshold used to determine if the file will be split into multiple parts. |
Returns
| Type | Description |
|---|---|
boolean | True if the file size exceeds the chunk size, False otherwise. |
open()
@classmethod
def open(
mode: string = None
) - > [File](file.md?sid=django_core_files_base_file)
Opens or reopens the file; if already open, it seeks to the beginning of the stream.
Parameters
| Name | Type | Description |
|---|---|---|
| mode | string = None | The mode in which the file should be opened (e.g., 'r', 'w', 'rb'). |
Returns
| Type | Description |
|---|---|
[File](file.md?sid=django_core_files_base_file) | The File instance in an open state. |
close()
@classmethod
def close() - > null
Closes the underlying file object to release system resources.
Returns
| Type | Description |
|---|---|
null | None |