File オブジェクト¶
django.core.files モジュールとそのサブモジュールでは、Django の基本的なファイルハンドリングに関するビルトインクラスが定義されています。
File クラス¶
- class File(file_object, name=None)[ソース]¶
The
Fileclass 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からの相対パスを含むファイル名です。
- file¶
The underlying file object that this class wraps.
この属性をサブクラスで扱う場合には注意が必要です。
Some subclasses of
File, includingContentFileandFieldFile, may replace this attribute with an object other than a Python file object. In these cases, this attribute may itself be aFilesubclass (and not necessarily the same subclass). Whenever possible, use the attributes and methods of the subclass itself rather than the those of the subclass'sfileattribute.
- mode¶
ファイルの読み込み/書き込みのモードです。
- open(mode=None, *args, **kwargs)[ソース]¶
Open or reopen the file (which also does
File.seek(0)). Themodeargument allows the same values as Python's built-inopen().*argsand**kwargsare passed aftermodeto Python's built-inopen().ファイルを再オープンする際、
modeはファイルが元々開かれていたモードを上書きします。Noneはオリジナルのモードで再オープンすることを意味します。コンテキストマネージャとして使用できます。たとえば、
with file.open() as f:のようにです。
- chunks(chunk_size=None)[ソース]¶
ファイルをイテレートし、指定されたサイズの「チャンク」を生成します。
chunk_sizeのデフォルトは 64 KB です。これは非常に大きなファイルに特に便利であり、ディスクからストリーミングしてメモリ全体にファイルを保存することを避けることができます。
- multiple_chunks(chunk_size=None)[ソース]¶
chunk_size(一括サイズ) で指定されたファイルの全内容にアクセスするために複数のチャンクが必要な場合はTrueを返します。
リストされたメソッドに加えて、
Fileは、そのfileオブジェクトの以下の属性とメソッドを公開しています:encoding,fileno,flush,isatty,newlines,read,readinto,readline,readlines,seek,tell,truncate,write,writelines,readable(),writable(), およびseekable()。
ContentFile クラス¶
ImageFile クラス¶
オブジェクトに添付されたファイルに関する追加メソッド¶
オブジェクト(以下の Car.photo のように)に関連付けられた File には、いくつかの追加メソッドも用意されています。
- File.save(name, content, save=True)¶
提供されたファイル名と内容で新しいファイルを保存します。これは既存のファイルを置き換えるものではありませんが、新しいファイルを作成し、オブジェクトがそれを指すように更新します。
saveがTrueの場合、ファイルが保存されたらモデルの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)¶
モデルインスタンスからファイルを削除し、基になるファイルも削除します。
saveがTrueの場合、ファイルが削除された後にモデルのsave()メソッドが一度呼び出されます。