Home  >  Article  >  Backend Development  >  Python读大数据txt

Python读大数据txt

WBOY
WBOYOriginal
2016-06-10 15:05:261093browse

如果直接对大文件对象调用 read() 方法,会导致不可预测的内存占用。好的方法是利用固定长度的缓冲区来不断读取文件内容。即通过yield。

    在用Python读一个两个多G的txt文本时,天真的直接用readlines方法,结果一运行内存就崩了。

    还好同事点拨了下,用yield方法,测试了下果然毫无压力。咎其原因,原来是readlines是把文本内容全部放于内存中,而yield则是类似于生成器。

代码如下:

def open_txt(file_name):
  with open(file_name,'r+') as f:
    while True:
      line = f.readline()
      if not line:
        return
      yield line.strip()

调用实例:

for text in open_txt('aa.txt'):
  print text

例二:

目标 txt 文件大概有6G,想取出前面1000条数据保存于一个新的 txt 文件中做余下的操作,虽然不知道这样做有没有必要但还是先小数据量测试一下吧。参考这个帖子:我想把一个list列表保存到一个Txt文档,该怎么保存 ,自己写了一个简单的小程序。
====================================================

import datetime
import pickle

start = datetime.datetime.now()
print "start--%s" % (start)

fileHandle = open ( 'train.txt' )
file2 = open('s_train.txt','w') 

i = 1
while ( i < 10000 ):
  a = fileHandle.readline()
  file2.write(''.join(a)) 
  i = i + 1

fileHandle.close() 
file2.close()

print "done--%s" % ( datetime.datetime.now() - start)

if __name__ == '__main__':
  pass

====================================================
pickle 这个库大家说的很多,官网看看,后面可以好好学习一下。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn