import tarfile import os import shutil IMAGE_EXTENSION = '.png' # this script create a 'temp' folder and rename all images to its description, then add the folder to a tar file if __name__ == "__main__": # remove the temp folder if it exists if os.path.exists('./temp'): for filename in os.listdir('./temp'): # empty the folder os.remove('./temp/' + filename) os.rmdir('./temp') # remove the folder # create the folder again os.makedirs('./temp') # copy all images to the temp folder for filename in os.listdir('./data/images'): # get the matching text file on the 'texts' folder, if not found, skip text_filename = filename[:-len(IMAGE_EXTENSION)] + '.txt' if not os.path.exists('./data/texts/' + text_filename): continue # read the text file with open('./data/texts/' + text_filename, 'r') as f: description = f.read() # copy the images to the temp folder, renaming it to the description replacing spaces with underscores shutil.copyfile('./data/images/' + filename, './temp/' + description.replace(' ', '_') + IMAGE_EXTENSION) # create a tar file with only the temp folder images with tarfile.open( "./images.tar.gz", "w:gz") as tar: for filename in os.listdir('./temp'): tar.add('./temp/' + filename, arcname=filename)