Pythonic way to ignore for loop control variable

前端 未结 9 1422
时光取名叫无心
时光取名叫无心 2020-12-03 11:22

A Python program I\'m writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I\'m doing s

9条回答
  •  难免孤独
    2020-12-03 12:12

    import itertools
    
    header_lines = list(itertools.islice(file_handle, header_len))
    # or
    header = "".join(itertools.islice(file_handle, header_len))
    

    Note that with the first, the newline chars will still be present, to strip them:

    header_lines = list(n.rstrip("\n")
                        for n in itertools.islice(file_handle, header_len))
    

提交回复
热议问题