File 对象¶django.core.files 模块及其子模块包含了 Django 中基本的文件处理的内置类。
File 类¶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 对象具有以下属性和方法:
文件名,包括 MEDIA_ROOT 的相对路径。
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.
文件的读/写模式。
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:。
对文件进行迭代,产生给定大小的“块”。chunk_size 默认为 64KB。
这对非常大的文件特别有用,因为它允许将它们从磁盘上串联起来,避免将整个文件存储在内存中。
除了列出的方法外,File 还暴露了它的 file 对象的以下属性和方法:encoding、fileno、flush、isat。encoding、fileno、flush、isatty、newlines、read、readinto、readline、readlines、seek、tell、truncate、write、writelines、readable()、writable() 和 seekable()。
ContentFile 类¶ImageFile 类¶任何与对象相关联的 File (如下面的 Car.photo)也会有几个额外的方法:
使用提供的文件名和内容保存一个新文件。这不会替换现有文件,而是创建一个新文件并更新对象以指向它。如果 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。
从模型实例中删除文件并删除底层文件。如果 save 是 True,一旦文件被删除,模型的 save() 方法将被调用。
12月 22, 2025