Does readlines() return a list or an iterator in Python 3?

前端 未结 3 1167
旧巷少年郎
旧巷少年郎 2021-01-07 16:31

I\'ve read in \"Dive into Python 3\" that \"The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2\". See here: http://di

3条回答
  •  没有蜡笔的小新
    2021-01-07 16:56

    Others have said as much already, but just to drive the point home, ordinary file objects are their own iterators. So having readlines() return an iterator would be silly, because it would just return the file you called it on. You can use a for loop to iterate over a file, like Scott said, and you can also pass them straight to itertools functions:

    from itertools import islice
    f = open('myfile.txt')
    oddlines = islice(f, 0, None, 2)
    firstfiveodd = islice(oddlines, 5)
    for line in firstfiveodd:
      print(line)
    

提交回复
热议问题