Pythonic way to ignore for loop control variable

前端 未结 9 1364
时光取名叫无心
时光取名叫无心 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))
    
    0 讨论(0)
  • 2020-12-03 12:13
    s=""
    f=open("file")
    for n,line in enumerate(f):
      if n<=3 : s=s+line
      else:
          # do something here to process the rest of the lines          
    print s
    f.close()
    
    0 讨论(0)
  • 2020-12-03 12:19
    f = open('fname')
    header = [next(f) for _ in range(header_len)]
    

    Since you're going to write header back to the new files, you don't need to do anything with it. To write it back to the new file:

    open('new', 'w').writelines(header + list_of_lines)
    

    if you know the number of lines in the old file, list_of_lines would become:

    list_of_lines = [next(f) for _ in range(chunk_len)]
    
    0 讨论(0)
提交回复
热议问题