24

4G 内存处理 10G 大小的文件,单机怎么做到?

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI1MTE2ODg4MA%3D%3D&%3Bmid=2650072376&%3Bidx=3&%3Bsn=9968be18fe289a8bce3e50ef6f2a01aa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

下面的讨论基于的假定: 可以单独处理一行数据,行间数 据相关性为零。

方法一:

仅使用 Python 内置模板,逐行读取到内存。

使用 yield,好处是解耦读取操作和处理操作:

def python_read(filename):
    with open(filename,'r',encoding='utf-8') as f:
        while  True:
            line = f.readline()
            if not line:
                return
            yield line

以上每次读取一行,逐行迭代,逐行处理数据

if __name__ == '__main__':
    g = python_read('./data/movies.dat')
    for c in g:
        print(c)
        # process c

方法二:

方法一有缺点,逐行读入,频繁的 IO 操作拖累处理效率。是否有一次 IO ,读取多行的方法?

pandasread_csv 函数,参数有 38 个之多,功能非常强大。

关于单机处理大文件, read_csvchunksize 参数能做到,它被设置为 5 , 意味着一次读取 5 行。

def pandas_read(filename,sep=',',chunksize=5):
    reader = pd.read_csv(filename,sep,chunksize=chunksize)
    while  True:
        try:
            yield reader.get_chunk()
        except StopIteration:
            print('---Done---')
            break

使用如同方法一:

if __name__ == '__main__':
    g = pandas_read('./data/movies.dat',sep="::")
    for c in g:
        print(c)
        # process c

以上就是单机处理大文件的两个方法,推荐使用方法二,更加灵活。除了工作中会用到,面试中也有时被问到。

近期文章


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK