File 对象Link to this heading
django.core.files 模块及其子模块包含了 Django 中基本的文件处理的内置类。
File 类Link to this heading
- class File(file_object, name=None)Link to this definition
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对象具有以下属性和方法:- nameLink to this definition
文件名,包括
MEDIA_ROOT的相对路径。
- sizeLink to this definition
文件的大小,单位为字节。
- fileLink to this definition
The underlying file object that this class wraps.
- modeLink to this definition
文件的读/写模式。
- open(mode=None, *args, **kwargs)Link to this definition
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:。
- __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对象的以下属性和方法:encoding、fileno、flush、isat。encoding、fileno、flush、isatty、newlines、read、readinto、readline、readlines、seek、tell、truncate、write、writelines、readable()、writable()和seekable()。
ContentFile 类Link to this heading
- class ContentFile(content, name=None)Link to this definition
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 类Link 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
使用提供的文件名和内容保存一个新文件。这不会替换现有文件,而是创建一个新文件并更新对象以指向它。如果
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)Link to this definition
从模型实例中删除文件并删除底层文件。如果
save是True,一旦文件被删除,模型的save()方法将被调用。