Python之读取大型文本文件

以前接触的数据,不管是csv仍是txt格式,都比较小,最大也就几百兆。在读取过程当中不会遇到内存崩溃的现象。spa

最近,项目中接收到的数据居然比电脑内存还要大 ,读取过程当中常常遇到memoryError错误,因而开始研究了关于大文件读取;于此参考了如下博客:.net

https://blog.csdn.net/u011847043/article/details/81069105对象


 

谈到“文本处理”时,咱们一般是指处理的内容。blog

Python 将文本文件的内容读入能够操做的字符串变量很是容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。。内存

read() 一次性读取读取整个文件,将文件存储在一个字符串变量中。当文件接近或者大于内存时会产生memoryError的错误。utf-8

readline() 和 readlines() 之间的差别是后者一次读取整个文件,同 read()。文档

readlines() 自动将文件内容分析成一个行的列表,该列表能够由 Python 的 for ... in ... 结构进行处理。字符串

另外一方面,.readline() 每次只读取一行,一般比 readlines() 慢得多。仅当没有足够内存能够一次读取整个文件时,应该使用 .readline()。博客

with open('filepath', 'r', encoding = 'utf-8') as f:
  while True:
    line = f.readline() # 逐行读取
    if not line: # 到 EOF,返回空字符串,则终止循环
      break
    Operate(line) #对每行数据进行处理it

分块读取(实用靠谱)

将文档按块进行读取

def read_in_chunks(filePath, chunk_size=1024*1024):   file_object = open(filePath,'r',encoding='utf-8')   while True:     chunk_data = file_object.read(chunk_size)     if not chunk_data:       break     yield chunk_dataif __name__ == "__main__":   filePath = "C:/Users/Public/Documents/data/user_data.csv"   for chunk in read_in_chunks(filePath):     print(chunk)

相关文章
相关标签/搜索