How to read a large file - line by line?

前端 未结 11 860
一整个雨季
一整个雨季 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条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 11:54

    #Using a text file for the example
    with open("yourFile.txt","r") as f:
        text = f.readlines()
    for line in text:
        print line
    
    • Open your file for reading (r)
    • Read the whole file and save each line into a list (text)
    • Loop through the list printing each line.

    If you want, for example, to check a specific line for a length greater than 10, work with what you already have available.

    for line in text:
        if len(line) > 10:
            print line
    

提交回复
热议问题