# Python csv.DictWriter 参考

URL: https://caijiao.org/reference/python/csv-dictwriter
Source: docs/reference/python/csv-dictwriter.md
Description: Python csv.DictWriter 参考，整理标准库调用语法、参数、示例、返回值和常见错误。

Python csv.DictWriter 参考，整理标准库调用语法、参数、示例、返回值和常见错误。

## 语法

```python
import csv

writer = csv.DictWriter(file, fieldnames=["name", "age"])
```

## 参数

- `file`：以 `newline=""` 打开的 CSV 文件对象。
- `delimiter / quotechar`：控制分隔符和引号规则。

## 返回值

返回行迭代器、字典行或写入结果；写入方法通常返回写入的字符数或 None。

## 示例

```python
import csv

with open("out.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "age"])
    writer.writeheader()
```

## 常见错误

- 打开文件时漏掉 `newline=""`，Windows 下可能出现空行。
- 手动 split CSV 会处理不好引号、逗号和换行。

## 相关内容

- [Python 教程](/python/)
- [Python 问题库](/how-to/python/)
- [JSON Formatter](/tool/json-formatter)
- [Timestamp Converter](/tool/timestamp-converter)
