Last active
September 1, 2022 05:11
-
-
Save Mahmood-Hussain/aaab2f49999c5b7ee1bd03b8c3d4d367 to your computer and use it in GitHub Desktop.
Move or Copy files form source directory to destination directory with progress using python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import glob | |
import os | |
import argparse | |
parser = argparse.ArgumentParser(description='Copy or move files') | |
parser.add_argument('--source', help='Source directory', type=str) | |
parser.add_argument('--dest', help='Destination directory', type=str) | |
parser.add_argument('-r', '--recursive', action='store_true', help='Recursive if you want to scan sub directories recursively', default=True) | |
parser.add_argument('-e', '--extensions', nargs='+', help='Extensions allowed', default=['jpg', 'png', 'gif']) | |
parser.add_argument('-c', '--copy', action='store_true', help='Copy files or move files default is copy files', default=True) | |
parser.add_argument('-d', '--depth', type=int, default=1, help='How deep to go inside the sub folders. 1 is for scanning just top level folder for given extensions of files.') | |
parser.add_argument('-p', '--progress', action='store_true', help='Progress bar. Whether you want to display progress (for this tqdm package should be instaled)', default=False) | |
args = parser.parse_args() | |
source = args.source | |
dest = args.dest | |
recursive = args.recursive | |
extensions = args.extensions | |
copy = args.copy | |
depth = args.depth | |
progress = args.progress | |
# Example: | |
# python3 copyormoverec.py --source /path/to/source --dest /path/to/destination -r -e 'png' -c -d 2 -p | |
# validate arguments | |
if not os.path.isdir(source): | |
print('Source directory does not exist') | |
exit() | |
if not os.path.isdir(dest): | |
os.mkdir(dest) | |
# if show progress import tqdm | |
if progress: | |
import tqdm | |
def move(source, dest, recursive, extensions, copy, depth, progress_bar): | |
if depth == 0: | |
return | |
for file in glob.glob(source + '/*'): | |
if os.path.isdir(file): | |
if recursive: | |
move(file, dest, recursive, extensions, copy, depth - 1, progress_bar) | |
else: | |
if os.path.splitext(file)[1][1:] in extensions: | |
if copy: | |
os.system('cp ' + file + ' ' + dest) | |
else: | |
os.system('mv ' + file + ' ' + dest) | |
if progress_bar: | |
progress_bar.update(1) | |
def main(): | |
move(source, dest, recursive, extensions, copy, args.depth, tqdm.tqdm(total=len(glob.glob(source + '/*')))) | |
if __name__ == '__main__': | |
main() | |
print('Done') | |
exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment