# Python 如何逐行读取大文件

URL: https://caijiao.org/how-to/python/read-large-file
Source: docs/how-to/python/read-large-file.md
Description: Python 如何逐行读取大文件：直接迭代文件对象，不要 read() 一次读入全部内容。 包含脚本示例、处理提醒和相关 Python、工具内容入口。

## 快速答案

直接迭代文件对象，不要 read() 一次读入全部内容。

```py
with open('large.log', encoding='utf-8') as f:
    for line in f:
        handle(line)
```

## 使用要点

- 把输入目录和输出目录放到变量里，批量处理前先打印将要操作的文件列表。
- 跨平台脚本优先使用 `pathlib`，避免手写路径分隔符。

## 相关内容

- [Python 问题](/how-to/python/)
- [Python 教程](/python/)
- [Python 文件处理项目](/python/ch11/project-filetool)
- [正则表达式测试工具](/tool/regex-tester)
- [JSON Formatter](/tool/json-formatter)
