1#!/usr/bin/python3 2 3import glob 4import os 5 6from shutil import rmtree, move, copy, copytree 7from sys import stderr 8 9 10def append(text, more_text): 11 if text: 12 return f'{text}, {more_text}' 13 return more_text 14 15 16def print_e(*args, **kwargs): 17 print(*args, file=stderr, **kwargs) 18 19 20def touch(filename, times=None): 21 with open(filename, 'a'): 22 os.utime(filename, times) 23 24 25def rm(path): 26 """Removes the file or directory tree at the specified path, if it exists. 27 28 Args: 29 path: Path to remove 30 """ 31 if os.path.isdir(path): 32 rmtree(path) 33 elif os.path.exists(path): 34 os.remove(path) 35 36 37def mv(src_path, dst_path): 38 """Moves the file or directory tree at the source path to the destination path. 39 40 This method does not merge directory contents. If the destination is a directory that already 41 exists, it will be removed and replaced by the source. If the destination is rooted at a path 42 that does not exist, it will be created. 43 44 Args: 45 src_path: Source path 46 dst_path: Destination path 47 """ 48 if os.path.exists(dst_path): 49 rm(dst_path) 50 if not os.path.exists(os.path.dirname(dst_path)): 51 os.makedirs(os.path.dirname(dst_path)) 52 for f in (glob.glob(src_path)): 53 if '*' in dst_path: 54 dst = os.path.join(os.path.dirname(dst_path), os.path.basename(f)) 55 else: 56 dst = dst_path 57 move(f, dst) 58 59 60def cp(src_path, dst_path): 61 """Copies the file or directory tree at the source path to the destination path. 62 63 This method does not merge directory contents. If the destination is a directory that already 64 exists, it will be removed and replaced by the source. If the destination is rooted at a path 65 that does not exist, it will be created. 66 67 Note that the implementation of this method differs from mv, in that it does not handle "*" in 68 the destination path. 69 70 Args: 71 src_path: Source path 72 dst_path: Destination path 73 """ 74 if os.path.exists(dst_path): 75 rm(dst_path) 76 if not os.path.exists(os.path.dirname(dst_path)): 77 os.makedirs(os.path.dirname(dst_path)) 78 for f in (glob.glob(src_path)): 79 if os.path.isdir(f): 80 copytree(f, dst_path) 81 else: 82 copy(f, dst_path) 83