Skip to main content

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]
'foo\n'
>>> wrapped[2]
'baz\n'

Negative indexes are supported as well.

>>> wrapped[-1]
'qux\n'
>>> wrapped[-3]
'bar\n'

The length returns the number of lines.

>>> len(wrapped)
4

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_)
2
>>> slice_[0]
'bar\n'
>>> slice_[1]
'baz\n'
>>> slice_ = wrapped[1:][0:2]
>>> len(slice_)
2
>>> slice_[0]
'bar\n'
>>> slice_[1]
'baz\n'

Slice stepping is also supported.

>>> slice_ = wrapped[1::2]
>>> len(slice_)
2
>>> slice_[0]
'bar\n'
>>> slice_[1]
'qux\n'

The wrappers are also iterators suitable for writelines().

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

Changelog

0.1 - 2009-05-27

  • Initial release

Project details


Release history Release notifications | RSS feed

This version

0.1

Download files

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

Source Distribution

rpatterson.listfile-0.1.tar.gz (4.4 kB view details)

Uploaded Source

File details

Details for the file rpatterson.listfile-0.1.tar.gz.

File metadata

File hashes

Hashes for rpatterson.listfile-0.1.tar.gz
Algorithm Hash digest
SHA256 5046b89f9a73c080289696a0f2dcf31897ce10f2cbe0a867f4f38a84e24cf1bb
MD5 9e97ce01fb72c8a65d497fb233a9ccaa
BLAKE2b-256 7eb33b3c0e28c024a1f4379205bf81aa433c2a4f41d943a50f866da5960b8b32

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page