Reading specific lines only

后端 未结 28 1521
天命终不由人
天命终不由人 2020-11-22 05:08

I\'m using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?

Thanks

相关标签:
28条回答
  • 2020-11-22 05:35

    If you don't mind importing then fileinput does exactly what you need (this is you can read the line number of the current line)

    0 讨论(0)
  • 2020-11-22 05:36

    How about this:

    >>> with open('a', 'r') as fin: lines = fin.readlines()
    >>> for i, line in enumerate(lines):
          if i > 30: break
          if i == 26: dox()
          if i == 30: doy()
    
    0 讨论(0)
  • 2020-11-22 05:37

    Fairly quick and to the point.

    To print certain lines in a text file. Create a "lines2print" list and then just print when the enumeration is "in" the lines2print list. To get rid of extra '\n' use line.strip() or line.strip('\n'). I just like "list comprehension" and try to use when I can. I like the "with" method to read text files in order to prevent leaving a file open for any reason.

    lines2print = [26,30] # can be a big list and order doesn't matter.
    
    with open("filepath", 'r') as fp:
        [print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]
    

    or if list is small just type in list as a list into the comprehension.

    with open("filepath", 'r') as fp:
        [print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]
    
    0 讨论(0)
  • 2020-11-22 05:38

    To print line# 3,

    line_number = 3
    
    with open(filename,"r") as file:
    current_line = 1
    for line in file:
        if current_line == line_number:
            print(file.readline())
            break
        current_line += 1
    

    Original author: Frank Hofmann

    0 讨论(0)
  • 2020-11-22 05:39

    If your large text file file is strictly well-structured (meaning every line has the same length l), you could use for n-th line

    with open(file) as f:
        f.seek(n*l)
        line = f.readline() 
        last_pos = f.tell()
    

    Disclaimer This does only work for files with the same length!

    0 讨论(0)
  • 2020-11-22 05:39
    f = open(filename, 'r')
    totalLines = len(f.readlines())
    f.close()
    f = open(filename, 'r')
    
    lineno = 1
    while lineno < totalLines:
        line = f.readline()
    
        if lineno == 26:
            doLine26Commmand(line)
    
        elif lineno == 30:
            doLine30Commmand(line)
    
        lineno += 1
    f.close()
    
    0 讨论(0)
提交回复
热议问题