How can I read large text files in Python, line by line, without loading it into memory?

前端 未结 15 1498
臣服心动
臣服心动 2020-11-22 03:32

I need to read a large file, line by line. Lets say that file has more than 5GB and I need to read each line, but obviously I do not want to use readlines() bec

15条回答
  •  滥情空心
    2020-11-22 04:08

    All you need to do is use the file object as an iterator.

    for line in open("log.txt"):
        do_something_with(line)
    

    Even better is using context manager in recent Python versions.

    with open("log.txt") as fileobject:
        for line in fileobject:
            do_something_with(line)
    

    This will automatically close the file as well.

提交回复
热议问题