-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSmartOpen.py
More file actions
36 lines (30 loc) · 770 Bytes
/
SmartOpen.py
File metadata and controls
36 lines (30 loc) · 770 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
Exports the SmartOpen class.
"""
from typing import TextIO
class SmartOpen:
"""
Open a file with the right data compression module (gzip, bzip2, lzma, or plain) based on the file extension.
Is a context manager.
"""
def __init__(self, filename: str, mode: str = 'rt') -> None:
"""
:param filename: Path to the file.
:param mode: Mode string ('rt' by default)
"""
if filename.endswith('.gz'):
import gzip
o = gzip.open
elif filename.endswith('.bz2'):
import bz2
o = bz2.open
elif filename.endswith('.xz'):
import lzma
o = lzma.open
else:
o = open
self.file_obj = o(filename, mode)
def __enter__(self) -> TextIO:
return self.file_obj
def __exit__(self, exc_type, exc_value, traceback):
self.file_obj.close()