File オブジェクト

django.core.files モジュールとそのサブモジュールでは、Django の基本的なファイルハンドリングに関するビルトインクラスが定義されています。

File クラス

class File(file_object, name=None)[ソース]

The File class is a thin wrapper around a Python file object with some Django-specific additions. Internally, Django uses this class when it needs to represent a file.

File オブジェクトには次の属性とメソッドを持ちます。

name

MEDIA_ROOT からの相対パスを含むファイル名です。

size[ソース]

バイト単位で表されたファイルサイズ。

file

The underlying file object that this class wraps.

この属性をサブクラスで扱う場合には注意が必要です。

Some subclasses of File, including ContentFile and FieldFile, may replace this attribute with an object other than a Python file object. In these cases, this attribute may itself be a File subclass (and not necessarily the same subclass). Whenever possible, use the attributes and methods of the subclass itself rather than the those of the subclass's file attribute.

mode

ファイルの読み込み/書き込みのモードです。

open(mode=None, *args, **kwargs)[ソース]

Open or reopen the file (which also does File.seek(0)). The mode argument allows the same values as Python's built-in open(). *args and **kwargs are passed after mode to Python's built-in open().

ファイルを再オープンする際、 mode はファイルが元々開かれていたモードを上書きします。 None はオリジナルのモードで再オープンすることを意味します。

コンテキストマネージャとして使用できます。たとえば、 with file.open() as f: のようにです。

__iter__()[ソース]

ファイルをイテレートして、1行ずつ返します。

chunks(chunk_size=None)[ソース]

ファイルをイテレートし、指定されたサイズの「チャンク」を生成します。 chunk_size のデフォルトは 64 KB です。

これは非常に大きなファイルに特に便利であり、ディスクからストリーミングしてメモリ全体にファイルを保存することを避けることができます。

multiple_chunks(chunk_size=None)[ソース]

chunk_size (一括サイズ) で指定されたファイルの全内容にアクセスするために複数のチャンクが必要な場合は True を返します。

close()[ソース]

ファイルを閉じてください。

リストされたメソッドに加えて、File は、その file オブジェクトの以下の属性とメソッドを公開しています: encoding, fileno, flush, isatty, newlines, read, readinto, readline, readlines, seek, tell, truncate, write, writelines, readable(), writable(), および seekable()

ContentFile クラス

class ContentFile(content, name=None)[ソース]

ContentFile クラスは File を継承していますが、File とは異なり、実際のファイルではなく文字列コンテンツ(バイトもサポート)で操作します。例えば:

from django.core.files.base import ContentFile

f1 = ContentFile("esta frase está en español")
f2 = ContentFile(b"these are bytes")

ImageFile クラス

class ImageFile(file_object, name=None)[ソース]

Django には画像専用の組み込みクラスがあります。 django.core.files.images.ImageFileFile のすべての属性とメソッドを継承し、さらに次のものを提供します:

width[ソース]

画像の幅 (ピクセル単位)。

height[ソース]

画像の高さ(ピクセル単位)。

オブジェクトに添付されたファイルに関する追加メソッド

オブジェクト(以下の Car.photo のように)に関連付けられた File には、いくつかの追加メソッドも用意されています。

File.save(name, content, save=True)

提供されたファイル名と内容で新しいファイルを保存します。これは既存のファイルを置き換えるものではありませんが、新しいファイルを作成し、オブジェクトがそれを指すように更新します。 saveTrue の場合、ファイルが保存されたらモデルの save() メソッドが一度呼び出されます。つまり、次の二行です:

>>> car.photo.save("myphoto.jpg", content, save=False)
>>> car.save()

これは以下と同等です:

>>> car.photo.save("myphoto.jpg", content, save=True)

content 引数は、 File または File のサブクラス(例えば、 ContentFile など)のインスタンスでなければなりません。

File.delete(save=True)

モデルインスタンスからファイルを削除し、基になるファイルも削除します。 saveTrue の場合、ファイルが削除された後にモデルの save() メソッドが一度呼び出されます。