File 对象¶django.core.files 模块及其子模块包含了 Django 中基本的文件处理的内置类。
File 类¶File(file_object, name=None)[源代码]¶File 类是对 Python file object 的一个简单的封装,并增加了一些 Django 特有的功能。在内部,当 Django 需要表示一个文件时,会使用这个类。
File 对象具有以下属性和方法:
name¶文件名,包括 MEDIA_ROOT 的相对路径。
size¶文件的大小,单位为字节。
file¶该类封装的底层 file object。
在子类中要小心这个属性。
一些 File 的子类,包括 ContentFile 和 FieldFile,可以用 Python file object 以外的对象来替换这个属性。在这些情况下,这个属性本身可能是一个 File 子类(而且不一定是同一个子类)。只要有可能,就使用子类本身的属性和方法,而不是子类的 file 属性。
mode¶文件的读/写模式。
open(mode=None, *args, **kwargs)[源代码]¶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:。
Support for passing *args and **kwargs was added.
chunks(chunk_size=None)[源代码]¶对文件进行迭代,产生给定大小的“块”。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)¶Saves a new file with the file name and contents provided. This will not
replace the existing file, but will create a new file and update the object
to point to it. If save is True, the model's save() method will
be called once the file is saved. That is, these two lines:
>>> car.photo.save("myphoto.jpg", content, save=False)
>>> car.save()
are equivalent to:
>>> car.photo.save("myphoto.jpg", content, save=True)
请注意,content 参数必须是 File 或 File 的子类的实例,如 ContentFile。
File.delete(save=True)¶从模型实例中删除文件并删除底层文件。如果 save 是 True,一旦文件被删除,模型的 save() 方法将被调用。
12月 05, 2023