File 对象¶
django.core.files 模块及其子模块包含了 Django 中基本的文件处理的内置类。
File 类¶
- class File(file_object, name=None)[source]¶
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)[source]¶
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)[source]¶
对文件进行迭代,产生给定大小的“块”。
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)也会有几个额外的方法:
- 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()方法将被调用。