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

前端 未结 3 663
梦如初夏
梦如初夏 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:15

    This works out well in the long run. It ignores the fact that you're processing a file, and works with any sequence. Also, having the explicit iterator object (rdr) hanging around allows you to skip lines inside the body of for loop without messing anything up.

    with open("myfile.txt","r") as source:
        rdr= iter(source)
        heading= next(rdr)
        for line in rdr:
            process( line )
    

提交回复
热议问题