How to read a large file - line by line?

前端 未结 11 1019
一整个雨季
一整个雨季 2020-11-21 11:44

I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method

11条回答
  •  萌比男神i
    2020-11-21 12:12

    The correct, fully Pythonic way to read a file is the following:

    with open(...) as f:
        for line in f:
            # Do something with 'line'
    

    The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.

    There should be one -- and preferably only one -- obvious way to do it.

提交回复
热议问题