From 96375a1c1fd3b2e9b17ed4002328090ba61240d4 Mon Sep 17 00:00:00 2001 From: Prodesire Date: Tue, 28 Nov 2017 22:55:51 +0800 Subject: [PATCH] add file includes several methods include remove, copy and etc. --- pydu/file.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 pydu/file.py diff --git a/pydu/file.py b/pydu/file.py new file mode 100644 index 0000000..a22f99f --- /dev/null +++ b/pydu/file.py @@ -0,0 +1,70 @@ +import os +import sys +import shutil + + +# todo tests and docs +def makedirs(path, mode=0o755, *, ignore_errors=False): + try: + os.makedirs(path, mode, exist_ok=True) + except Exception: + if not ignore_errors: + raise OSError('Create dir: {} error'.format(path)) + + +def remove(path, *, ignore_errors=False, onerror=None): + if ignore_errors: + def onerror(*args): + pass + elif onerror is None: + def onerror(*args): + raise OSError('Remove path: {} error'.format(path)) + + if os.path.isdir(path): + shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror) + else: + try: + os.remove(path) + except Exception: + onerror(os.remove, path, sys.exc_info()) + + +def removes(*paths, ignore_errors=False, onerror=None): + for path in paths: + remove(path, ignore_errors=ignore_errors, onerror=onerror) + + +def open_file(path, mode='wb+', *, buffer_size=-1, ignore_errors=False): + f = None + try: + if path and not os.path.isdir(path): + makedirs(os.path.dirname(path)) + f = open(path, mode, buffer_size) + except Exception: + if not ignore_errors: + raise OSError('Open file: {} error'.format(path)) + return f + + +def link(src, dst, *, overwrite=False, ignore_errors=False): + try: + if os.path.exists(dst): + if overwrite: + remove(dst) + else: + return + os.link(src, dst) + except Exception: + if not ignore_errors: + raise OSError('Link {} to {} error'.format(dst, src)) + + +def copy(src, dst, *, ignore_errors=False, follow_symlinks=True): + try: + if os.path.isdir(src): + shutil.copytree(src, dst, symlinks=not follow_symlinks) + else: + shutil.copy(src, dst, follow_symlinks=follow_symlinks) + except Exception: + if not ignore_errors: + raise OSError('Copy {} to {} error'.format(src, dst))