Skip to content

Instantly share code, notes, and snippets.

@aandergr
Created August 30, 2018 07:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aandergr/69e08367d6b9632375691dda35eb649c to your computer and use it in GitHub Desktop.
Save aandergr/69e08367d6b9632375691dda35eb649c to your computer and use it in GitHub Desktop.
Mass rename files in your local Instagram archive according to a new filename pattern
import argparse
import glob
import os
import re
import sys
import instaloader
def json_type(filename: str):
if not (filename.endswith('.json') or filename.endswith('.json.xz')):
raise argparse.ArgumentTypeError("{} not a JSON file.")
return filename
parser = argparse.ArgumentParser()
parser.add_argument('filename_pattern')
parser.add_argument('json', nargs='+', type=json_type)
args = parser.parse_args()
L = instaloader.Instaloader(filename_pattern=args.filename_pattern)
try:
for json_file in args.json:
try:
item = instaloader.load_structure_from_file(L.context, json_file)
if not (isinstance(item, instaloader.Post) or isinstance(item, instaloader.StoryItem)):
print("{} / {} skipped.", json_file, item)
continue
pattern = r'(.*)(_location\.txt|_comments\.json|\.(json(\.xz)?|txt|jpg|mp4))$'
for file in glob.glob('{}*'.format(re.match(pattern, json_file).group(1))):
fm = re.match(pattern, file)
if fm:
dirname = os.path.dirname(file) + '/' if os.path.dirname(file) else ''
new_filename = dirname + L.format_filename(item) + fm.group(2)
print("{} -> {}".format(file, new_filename))
os.rename(file, new_filename)
else:
print("{} not renamed.".format(file))
except instaloader.InstaloaderException as err:
print("{}: {}".format(json_file, err), file=sys.stderr)
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment