python3大数据文件的读取方法

这篇文章主要介绍python3大数据文件的读取方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python中读取大文件的方法:

1、利用yield生成器读取

def readPart(filePath, size=1024, encoding="utf-8"):
    with open(filePath,"r",encoding=encoding) as f:
        while True:
            part = f.read(size)  
            if part:
                yield part
            else:
                return None
filePath = r"filePath"
size = 2048 # 每次读取指定大小的内容到内存
encoding = 'utf-8'
for part in readPart(filePath,size,encoding):
    print(part)
    # Processing data

2、利用open()自带方法生成迭代对象,这个是一行一行的读取

with open(filePath) as f:
    for line in f:
        print(line)
        # Processing data

以上是python3大数据文件的读取方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!