File 对象Link to this heading

django.core.files 模块及其子模块包含了 Django 中基本的文件处理的内置类。

FileLink to this heading

class File(file_object, name=None)Link to this definition

File 类是对 Python file object 的一个简单的封装,并增加了一些 Django 特有的功能。在内部,当 Django 需要表示一个文件时,会使用这个类。

File 对象具有以下属性和方法:

nameLink to this definition

文件名,包括 MEDIA_ROOT 的相对路径。

sizeLink to this definition

文件的大小,单位为字节。

fileLink to this definition

该类封装的底层 file object

modeLink to this definition

文件的读/写模式。

open(mode=None, *args, **kwargs)Link to this definition

打开或重新打开文件(这也会执行 File.seek(0))。mode 参数允许与 Python 内置的 open() 相同的值。*args**kwargsmode 之后传递给 Python 内置的 open()

当重新打开一个文件时,mode 将覆盖文件原来打开的任何模式;None 表示用原来的模式重新打开。

它可以作为一个上下文管理器使用,例如 with file.open() as f:

__iter__()Link to this definition

在文件上迭代,每次只产生一行。

chunks(chunk_size=None)Link to this definition

对文件进行迭代,产生给定大小的“块”。chunk_size 默认为 64KB。

这对非常大的文件特别有用,因为它允许将它们从磁盘上串联起来,避免将整个文件存储在内存中。

multiple_chunks(chunk_size=None)Link to this definition

如果文件足够大,需要多个分块才能访问其所有内容,则返回 True

close()Link to this definition

关闭文件。

除了列出的方法外,File 还暴露了它的 file 对象的以下属性和方法:encodingfilenoflushisatencodingfilenoflushisattynewlinesreadreadintoreadlinereadlinesseektelltruncatewritewritelinesreadable()writable()seekable()

ContentFileLink to this heading

class ContentFile(content, name=None)Link to this definition

ContentFile 类继承自 File,但与 File 不同的是,它操作的是字符串内容(也支持字节),而不是实际的文件。例如:

Code
from django.core.files.base import ContentFile

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

ImageFileLink to this heading

class ImageFile(file_object, name=None)Link to this definition

Django 提供了一个专门针对图片的内置类。 django.core.files.images.ImageFile 继承了 File 的所有属性和方法,并额外提供了以下内容。

widthLink to this definition

图像的宽度,单位为像素。

heightLink to this definition

图像的高度,单位为像素。

附加在对象上的文件方法Link to this heading

任何与对象相关联的 File (如下面的 Car.photo)也会有几个额外的方法:

File.save(name, content, save=True)Link to this definition

使用提供的文件名和内容保存一个新文件。这不会替换现有文件,而是创建一个新文件并更新对象以指向它。如果 saveTrue,则在文件保存后将调用模型的 save() 方法。也就是说,以下两行代码:

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

等同于:

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

请注意,content 参数必须是 FileFile 的子类的实例,如 ContentFile

File.delete(save=True)Link to this definition

从模型实例中删除文件并删除底层文件。如果 saveTrue,一旦文件被删除,模型的 save() 方法将被调用。