How to read a specific range of lines in an external file in python?

前端 未结 3 656
醉梦人生
醉梦人生 2021-01-22 05:07

Lets say you have a python file with 50 lines of code in it, and you want to read a specific range lines into a list. If you want to read ALL the lines in the file, you can just

3条回答
  •  隐瞒了意图╮
    2021-01-22 05:46

    You were close. readlines returns a list and you can slice that, but it's invalid syntax to try and pass the slice directly in the function call.

    f.readlines()[23:27]
    

    If the file is very large, avoid the memory overhead of reading the entire file:

    start, stop = 23, 27
    for i in range(start):
        next(f)
    content = []
    for i in range(stop-start):
        content.append(next(f))
    

提交回复
热议问题