Reading a Line From File Without Advancing [Pythonic Approach]

后端 未结 5 2071
日久生厌
日久生厌 2021-01-01 10:24

What\'s a pythonic approach for reading a line from a file but not advancing where you are in the file?

For example, if you have a file of

cat1
cat2         


        
5条回答
  •  旧巷少年郎
    2021-01-01 11:16

    You could use wrap the file up with itertools.tee and get back two iterators, bearing in mind the caveats stated in the documentation

    For example

    from itertools import tee
    import contextlib
    from StringIO import StringIO
    s = '''\
    cat1
    cat2
    cat3
    '''
    
    with contextlib.closing(StringIO(s)) as f:
      handle1, handle2 = tee(f)
      print next(handle1)
      print next(handle2)
    
     cat1
     cat1
    

提交回复
热议问题