• 技术文章 >常见问题 >Python常见问题

    python3过大数据如何读取?

    yangyang2020-05-29 13:51:21原创2552

    python中读取大文件的方法:

    1、利用yield生成器读取

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    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()自带方法生成迭代对象,这个是一行一行的读取

    1

    2

    3

    4

    with open(filePath) as f:

        for line in f:

            print(line)

            # Processing data

    更多Python知识请关注Python自学网

    专题推荐:python3
    上一篇:python3中怎么编写类? 下一篇:python3如何引入模块?

    相关文章推荐

    • python打印列表有中文乱码怎么解决?• python是解释型吗?• python序列解包是什么意思?• python怎么使用文件夹下的脚本?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网