Mixing files and loops

后端 未结 4 656
Happy的楠姐
Happy的楠姐 2020-11-29 05:52

I\'m writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of t

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 06:29

    Assuming you need only one line, this could be of help

    import itertools
    
    def getline(fobj, line_no):
        "Return a (1-based) line from a file object"
        return itertools.islice(fobj, line_no-1, line_no).next() # 1-based!
    
    >>> print getline(open("/etc/passwd", "r"), 4)
    'adm:x:3:4:adm:/var/adm:/bin/false\n'
    

    You might want to catch StopIteration errors (if the file has less lines).

提交回复
热议问题