Skip to main content

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

AttributeTypeDescription
DEFAULT_CHUNK_SIZEint = 65536The 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

NameTypeDescription
filefile-like objectThe underlying file-like object to be wrapped.
namestring = NoneThe 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

TypeDescription
integerThe 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

NameTypeDescription
chunk_sizeinteger = NoneThe number of bytes to read in each iteration; defaults to 64KB if not provided.

Returns

TypeDescription
generatorA 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

NameTypeDescription
chunk_sizeinteger = NoneThe size threshold used to determine if the file will be split into multiple parts.

Returns

TypeDescription
booleanTrue 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

NameTypeDescription
modestring = NoneThe mode in which the file should be opened (e.g., 'r', 'w', 'rb').

Returns

TypeDescription
[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

TypeDescription
nullNone