Mixing files and loops

后端 未结 4 653
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:20

    You get the ValueError because your code probably has for line in original: in addition to original.readline(). An easy solution which fixes the problem without making your program slower or consume more memory is changing

    for line in original:
        ...
    

    to

    while True:
        line = original.readline()
        if not line: break
        ...
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-29 06:31

    Use for and enumerate.

    Example:

    for line_num, line in enumerate(file):
        if line_num < cut_off:
            print line
    

    NOTE: This assumes you are already cleaning up your file handles, etc.

    Also, the takewhile function could prove useful if you prefer a more functional flavor.

    0 讨论(0)
  • 2020-11-29 06:34

    Here's a version without the ugly while True pattern and without other modules:

    for line in iter(original.readline, ''):
        if …:   # to the beginning of the title or abstract
            for i in range(lineNumber):
                print original.readline(),
            break
    
    0 讨论(0)
提交回复
热议问题