Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

Support list operations over lines of file-like objects

Project description

Support list operations over lines of file-like objects.

All operations avoid iterating except when necessary. Operations that force iteration over the whole file include len() and using negative indexes. In order to avoid excess seeking, all list operations may change the position of the underlying file object.

Start with a file-like object.

>>> import cStringIO
>>> file_ = cStringIO.StringIO("""\
... foo
... bar
... baz
... qux
... """)

Wrap the file-like object in a listfile instance.

>>> from rpatterson import listfile
>>> wrapped = listfile.ListFile(file_)

Lines can be accessed by index.

>>> wrapped[0]
>>> wrapped[2]

Negative indexes are supported as well.

>>> wrapped[-1]
>>> wrapped[-3]

The length returns the number of lines.

>>> len(wrapped)

An index beyond the end of the file raises IndexError.

>>> wrapped[4]
Traceback (most recent call last):
IndexError: list index out of range

Retrieving a slice returns a new wrapper around the same file object.

>>> slice_ = wrapped[1:3]
>>> len(slice_)
>>> slice_[0]
>>> slice_[1]
>>> slice_ = wrapped[1:][0:2]
>>> len(slice_)
>>> slice_[0]
>>> slice_[1]

Slice stepping is also supported.

>>> slice_ = wrapped[1::2]
>>> len(slice_)
>>> slice_[0]
>>> slice_[1]

The wrappers are also iterators suitable for writelines().

>>> list(slice_)
['bar\n', 'qux\n']
>>> out = cStringIO.StringIO()
>>> out.writelines(slice_)
>>> out.getvalue()


0.1 - 2009-05-27

  • Initial release

Project details

Release history Release notifications

This version


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for rpatterson.listfile, version 0.1
Filename, size File type Python version Upload date Hashes
Filename, size rpatterson.listfile-0.1.tar.gz (4.4 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page