在python中读取大数据的不同方法

Loo*_*ast 6 python line

我正在处理大数据,因此找到一种阅读数据的好方法非常重要.我对不同的阅读方法感到有些困惑.

1.f=gzip.open(file,'r')
      for line in f:
          process line
     #how can I process nth line? can I?
2.f=gzip.open(file,'r').readlines()
  #f is a list
  f[10000]
  #we can process nth line

3.f=gzip.open(file,'r')
  while True:
       linelist=list(islice(f,4))

4.for line in fileinput.input():
  process line
Run Code Online (Sandbox Code Playgroud)

2和3有什么区别?我发现他们的内存使用情况是一样的.islice()还需要先将整个文件加载到内存中(但稍后才会逐位加载).而且我听说第四种方法消耗的内存最少,它实际上是一点一点地处理,对吧?对于10GB级文件,您会推荐哪种文件读取方法?欢迎任何想法/信息.谢谢

编辑:我认为我的一个问题是我需要随机选择特定的行.说:

f1=open(inputfile1, 'r')
while True:
    line_group1 = list(islice(f1, 3))
    if not line_group1:
        break
    #then process specific lines say, the second line.
    processed 2nd line
    if ( ....):
           LIST1.append(line_group1[0])
           LIST1.append(processed 2nd line)
           LIST1.append(line_group1[2])
Run Code Online (Sandbox Code Playgroud)

然后...... 喜欢

with open(file,'r') as f,
    for line in f:
       # process line
Run Code Online (Sandbox Code Playgroud)

可能不起作用,我是对的吗?

Bas*_*ork 5

查看David M. Beazley关于使用生成器解析大型日志文件的演讲(请参阅演示文稿的pdf):

http://www.dabeaz.com/generators/


Sri*_*aju 5

你忘了 -

with open(...) as f:
    for line in f:
        <do something with line>
Run Code Online (Sandbox Code Playgroud)

with语句处理打开和关闭文件,包括是否在内部块中引发异常.该for line in f会将文件对象f视为可迭代,它会自动使用缓冲IO和内存管理,所以你不必担心大文件.

对于大文件,不建议使用2,3,因为它们在处理开始之前读取并加载内存中的整个文件内容.要读取大文件,您需要找到一次不读取整个文件的方法.

应该有一个 - 最好只有一个 - 显而易见的方法.