Explicitly use __builtin__.open to avoid open() calling itself.
[apachelog.git] / apachelog / file.py
1 import __builtin__
2 import gzip as _gzip
3 import os.path as _os_path
4
5
6 """Openers by file extention.
7
8 Values should be callables such that::
9
10   for line in opener(filename, mode):
11       ...
12
13 will work.
14 """
15 OPENERS = {
16     '.gz': _gzip.open,
17     }
18
19
20 def open(filename, openers=None):
21     """Utility method that decompresses files based on their extension.
22
23     Uses ``OPENERS`` to determine the appropriate opener for the
24     file's extension.  If the extension is not listed in ``OPENERS``,
25     fall back to the ``open`` builtin.
26     """
27     if openers is None:
28         openers = OPENERS
29     extension = _os_path.splitext(filename)[-1]
30     opener = openers.get(extension, __builtin__.open)
31     return opener(filename, 'r')