关于python:python如何读取大文件

能够通过两种办法利用python读取大文件:第一种是利用yield生成器读取;第二种是:利用open()自带办法生成迭代对象,这个是一行一行的读取。

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

以上就是本次分享的全部内容,当初想要学习编程的小伙伴指路Python技术大本营,欢送各位的到来哦~

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据