python 如何读取超大的文件

2025-1-13 杜世伟 Python

在 Python 中读取超大的文件(例如,文件的大小大于系统内存)时,通常需要逐行或分块读取,以避免将整个文件加载到内存中,从而导致内存不足的问题。以下是几种常见的方法:

1. 使用 open 和迭代器逐行读取
这是最常见的方法。通过文件对象的迭代器,逐行读取文件。

with open('large_file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        process_line(line)  # 对每行进行处理

这种方式非常高效,因为它不会一次性将整个文件加载到内存,而是逐行读取。

2. 分块读取文件内容 
如果需要以更大的块为单位读取,可以使用 read 方法指定块的大小。
with open('large_file.txt', 'r', encoding='utf-8') as file:
    while True:
        chunk = file.read(1024 * 1024)  # 每次读取 1 MB

阅读全文>>

标签: python open pands mmap

评论(0) 浏览(263)

Powered by emlog 沪ICP备2023034538号-1