Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/statsmodels/iolib/openfile.py : 31%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2Handle file opening for read/write
3"""
4from numpy.lib._iotools import _is_string_like
7class EmptyContextManager(object):
8 """
9 This class is needed to allow file-like object to be used as
10 context manager, but without getting closed.
11 """
12 def __init__(self, obj):
13 self._obj = obj
15 def __enter__(self):
16 '''When entering, return the embedded object'''
17 return self._obj
19 def __exit__(self, *args):
20 '''Do not hide anything'''
21 return False
23 def __getattr__(self, name):
24 return getattr(self._obj, name)
27def _open(fname, mode, encoding):
28 if fname.endswith('.gz'):
29 import gzip
30 return gzip.open(fname, mode, encoding=encoding)
31 else:
32 return open(fname, mode, encoding=encoding)
35def get_file_obj(fname, mode='r', encoding=None):
36 """
37 Light wrapper to handle strings and let files (anything else) pass through.
39 It also handle '.gz' files.
41 Parameters
42 ----------
43 fname : str or file-like object
44 File to open / forward
45 mode : str
46 Argument passed to the 'open' or 'gzip.open' function
47 encoding : str
48 For Python 3 only, specify the encoding of the file
50 Returns
51 -------
52 A file-like object that is always a context-manager. If the `fname` was
53 already a file-like object, the returned context manager *will not
54 close the file*.
55 """
56 if _is_string_like(fname):
57 return _open(fname, mode, encoding)
58 try:
59 # Make sure the object has the write methods
60 if 'r' in mode:
61 fname.read
62 if 'w' in mode or 'a' in mode:
63 fname.write
64 except AttributeError:
65 raise ValueError('fname must be a string or a file-like object')
66 return EmptyContextManager(fname)