Is it safe to mix readline() and line iterators in python file processing?

前端 未结 3 666
梦如初夏
梦如初夏 2020-12-11 14:37

Is it safe to read some lines with readline() and also use for line in file, and is it guaranteed to use the same file position?

Usually, I

3条回答
  •  天命终不由人
    2020-12-11 15:38

    No, it isn't safe:

    As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

    You could use next() to skip the first line here. You should also test for StopIteration, which will be raised if the file is empty.

    with open('myfile.txt') as f:
        try:
            header = next(f)
        except StopIteration as e:
            print "File is empty"
        for line in f:
            # do stuff with line
    

提交回复
热议问题