Skip to content

Instantly share code, notes, and snippets.

@bqbn
Created February 21, 2020 06:48
Show Gist options
  • Save bqbn/bf543bd6010400c6e22f63c715d64e2d to your computer and use it in GitHub Desktop.
Save bqbn/bf543bd6010400c6e22f63c715d64e2d to your computer and use it in GitHub Desktop.
Move a file and its referrenced attachments and images to a different directory
#!/usr/bin/env python
#
# Move a file and its referrenced attachments and images to a different directory.
#
# Usage:
#
# movefiles.py <files> <dst_dir>
#
from pathlib import Path
import re
import shutil
import sys
src_files = sys.argv[1:-1]
dst_dir = sys.argv[-1]
Path(dst_dir).mkdir(parents=True, exist_ok=True)
p = re.compile('(?P<file>attachments/\d+/[^"\)]+|images/icons/[^\)\s"]+)')
# scan each source file for referenced attachments and images, and record them
# in a dictionary
for src_file in src_files:
referenced_files = {}
with open(src_file, 'r') as f:
for line in f:
m = p.search(line.strip())
if m:
referenced_files[m.group('file')] = True
# move all referenced attachments and images to dst_dir
# example:
# dst_dir = "../../services/myservice"
# name = "attachments/66655306/66655415.png"
# new_dir becomes "../../services/myservice/attachments/66655306"
for name in referenced_files.keys():
new_dir = Path(dst_dir).joinpath(Path(name).parent)
new_dir.mkdir(parents=True, exist_ok=True)
try:
shutil.move(Path(src_file).parent.joinpath(Path(name)).as_posix(), new_dir)
except (FileNotFoundError, shutil.Error) as e:
print(e)
pass
shutil.move(src_file, dst_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment