Reading in a text file in a set line range

前端 未结 3 1405
暗喜
暗喜 2020-12-15 01:16

Is it possible to read in from a text file a set line range for example from line 20 to 52?

I am opening the file and reading the file like this:

te         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 02:06

    You can do two things. You can use enumerate(), and use an if statement:

    text_file = open(file_to_save, "r")
    lines = []
    for index, text in enumerate(text_file):
        if 19 <= index <= 51:
            lines.append(text)
    

    Or instead, you can use readlines() and then slice:

    text_file = open(file_to_save, "r")
    lines = text_file.readlines()
    lines = lines[19:52]
    

提交回复
热议问题