---
title: "File 对象"
version: 5.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/5.0/ref/files/file/
canonical: https://djangodocs.dev/zh-hans/5.0/ref/files/file/
---
# `File` 对象

[`django.core.files`](/zh-hans/5.0/ref/files/#module-django.core.files) 模块及其子模块包含了 Django 中基本的文件处理的内置类。

## `File` 类

#### `class File(file_object, name=None)`

[`File`](#django.core.files.File) 类是对 Python [file object](https://docs.python.org/3/glossary.html#term-file-object) 的一个简单的封装，并增加了一些 Django 特有的功能。在内部，当 Django 需要表示一个文件时，会使用这个类。

[`File`](#django.core.files.File) 对象具有以下属性和方法：

#### `name`

文件名，包括 [`MEDIA_ROOT`](/zh-hans/5.0/ref/settings/#std-setting-MEDIA_ROOT) 的相对路径。

#### `size`

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

#### `file`

该类封装的底层 [file object](https://docs.python.org/3/glossary.html#term-file-object)。

> **在子类中要小心这个属性。**
>
> 一些 [`File`](#django.core.files.File) 的子类，包括 [`ContentFile`](#django.core.files.base.ContentFile) 和 `FieldFile`，可以用 Python [file object](https://docs.python.org/3/glossary.html#term-file-object) 以外的对象来替换这个属性。在这些情况下，这个属性本身可能是一个 [`File`](#django.core.files.File) 子类（而且不一定是同一个子类）。只要有可能，就使用子类本身的属性和方法，而不是子类的 `file` 属性。

#### `mode`

文件的读／写模式。

#### `open(mode=None, *args, **kwargs)`

打开或重新打开文件（这也会执行 `File.seek(0)`）。`mode` 参数允许与 Python 内置的 [`open()`](https://docs.python.org/3/library/functions.html#open) 相同的值。`*args` 和 `**kwargs` 在 `mode` 之后传递给 Python 内置的 [`open()`](https://docs.python.org/3/library/functions.html#open)。

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

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

> **Changed in Django 5.0**
>
> 已添加支持传递 `*args` 和 `**kwargs`。

#### `__iter__()`

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

#### `chunks(chunk_size=None)`

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

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

#### `multiple_chunks(chunk_size=None)`

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

#### `close()`

关闭文件。

除了列出的方法外，[`File`](#django.core.files.File) 还暴露了它的 `file` 对象的以下属性和方法：`encoding`、`fileno`、`flush`、`isat`。`encoding`、`fileno`、`flush`、`isatty`、`newlines`、`read`、`readinto`、`readline`、`readlines`、`seek`、`tell`、`truncate`、`write`、`writelines`、`readable()`、`writable()` 和 `seekable()`。

## `ContentFile` 类

#### `class ContentFile(content, name=None)`

`ContentFile` 类继承自 [`File`](#django.core.files.File)，但与 [`File`](#django.core.files.File) 不同的是，它操作的是字符串内容（也支持字节），而不是实际的文件。例如：

```
from django.core.files.base import ContentFile

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

## `ImageFile` 类

#### `class ImageFile(file_object, name=None)`

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

#### `width`

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

#### `height`

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

## 附加在对象上的文件方法

任何与对象相关联的 [`File`](#django.core.files.File) （如下面的 `Car.photo`）也会有几个额外的方法：

#### `File.save(name, content, save=True)`

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

```pycon
>>> car.photo.save("myphoto.jpg", content, save=False)
>>> car.save()
```

等同于：

```pycon
>>> car.photo.save("myphoto.jpg", content, save=True)
```

请注意，`content` 参数必须是 [`File`](#django.core.files.File) 或 [`File`](#django.core.files.File) 的子类的实例，如 [`ContentFile`](#django.core.files.base.ContentFile)。

#### `File.delete(save=True)`

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