|
7 | 7 | 'Float', 'tuplify', 'detuplify', 'replicate', 'uniqueify', 'setify', 'merge', 'is_listy', 'range_of', |
8 | 8 | 'groupby', 'last_index', 'shufflish', 'IterLen', 'ReindexCollection', 'num_methods', 'rnum_methods', |
9 | 9 | 'inum_methods', 'fastuple', 'trace', 'compose', 'maps', 'partialler', 'mapped', 'instantiate', 'using_attr', |
10 | | - 'Self', 'Self', 'save_pickle', 'load_pickle', 'bunzip', 'join_path_file', 'urlread', 'urljson', 'run', |
11 | | - 'do_request', 'sort_by_run', 'PrettyString', 'round_multiple', 'even_mults', 'num_cpus', 'add_props', |
| 10 | + 'Self', 'Self', 'open_file', 'save_pickle', 'load_pickle', 'bunzip', 'join_path_file', 'urlread', 'urljson', |
| 11 | + 'run', 'do_request', 'sort_by_run', 'PrettyString', 'round_multiple', 'even_mults', 'num_cpus', 'add_props', |
12 | 12 | 'ContextManagers', 'typed', 'set_num_threads', 'ProcessPoolExecutor', 'ThreadPoolExecutor', 'parallel', |
13 | 13 | 'run_procs', 'parallel_gen', 'threaded'] |
14 | 14 |
|
|
17 | 17 | from .foundation import * |
18 | 18 | from functools import wraps |
19 | 19 |
|
20 | | -import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex |
| 20 | +import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex,bz2,gzip |
21 | 21 | from contextlib import contextmanager |
22 | 22 | from pdb import set_trace |
23 | 23 | from urllib.request import Request,urlopen |
@@ -528,21 +528,24 @@ def ls(self:Path, n_max=None, file_type=None, file_exts=None): |
528 | 528 | if n_max is not None: res = itertools.islice(res, n_max) |
529 | 529 | return L(res) |
530 | 530 |
|
| 531 | +# Cell |
| 532 | +def open_file(fn, mode='r'): |
| 533 | + "Open a file, with optional compression if gz or bz2 suffix" |
| 534 | + if isinstance(fn, io.IOBase): return fn |
| 535 | + fn = Path(fn) |
| 536 | + if fn.suffix=='.bz2': return bz2.BZ2File(fn, mode) |
| 537 | + elif fn.suffix=='.gz' : return gzip.GzipFile(fn, mode) |
| 538 | + else: return open(fn,mode) |
| 539 | + |
531 | 540 | # Cell |
532 | 541 | def save_pickle(fn, o): |
533 | 542 | "Save a pickle file, to a file name or opened file" |
534 | | - fn = Path(fn) |
535 | | - if not isinstance(fn, io.IOBase): fn = open(fn,'wb') |
536 | | - try: pickle.dump(o, fn) |
537 | | - finally: fn.close() |
| 543 | + with open_file(fn, 'wb') as f: pickle.dump(o, f) |
538 | 544 |
|
539 | 545 | # Cell |
540 | 546 | def load_pickle(fn): |
541 | 547 | "Load a pickle file from a file name or opened file" |
542 | | - fn = Path(fn) |
543 | | - if not isinstance(fn, io.IOBase): fn = open(fn,'rb') |
544 | | - try: return pickle.load(fn) |
545 | | - finally: fn.close() |
| 548 | + with open_file(fn, 'rb') as f: return pickle.load(f) |
546 | 549 |
|
547 | 550 | # Cell |
548 | 551 | @patch |
|
0 commit comments