0

Currently I am working on a project in which I need to save n number of images (to be used in the program's scope). Since the number of images to be saved is dynamic, it may end up exhausting the whole space which i have for my project.

I wanted to know that can there be something added to my code so that after 100% completion of my code the images get automatically deleted as I do not need them after the code's execution.

How can this be done?

I need to save images as they are passed as an argument to one of my functions inside my code. If you know how can I pass image without saving it to my function then please comment here

Ambika Saxena
  • 215
  • 4
  • 17

2 Answers2

2

might be an idea to delete the files immediately after you've done the code you need to do i.e

import os

# Open image
# Manipulate image
os.remove(path_to_image)
Tomos Williams
  • 1,988
  • 1
  • 13
  • 20
  • Thanks! But how do you use this function n python in windows (Specifically Spyder). What do we need to import? – Ambika Saxena Jun 13 '17 at 11:02
  • you have to import os – Drako Jun 13 '17 at 11:02
  • @Drako I imported os. But since the images are being saved in the code and os.remove() is also been called from the same code, maybe that's why the function is unable to find the images and is showing the error: The system cannot find the file specified: 'D:\\ImageProcessing\\Output\\segment1.png' – Ambika Saxena Jun 13 '17 at 11:11
  • you should not look for those images after deleting them; or you should not delete them if you need them; do deletion as last task – Drako Jun 13 '17 at 11:13
  • I wrote this command in the end. Although it was not working before, its working now. thanks – Ambika Saxena Jun 13 '17 at 11:22
  • just amended the answer to reflect the import requirement – Tomos Williams Jun 13 '17 at 12:52
2

Keep track of all the image files you're creating, then delete them in a finally block to ensure they'll be deleted even if an exception is raised.

import os

temp_images = []

try:
    # ...do stuff

    # ...create image at path_to_file
    temp_images.append(path_to_file)  # called multiple times

    # ...other stuff

finally:
    for image in temp_images:
        os.remove(image)
Billy
  • 5,179
  • 2
  • 27
  • 53