How to make a new file name every time i run a program?

79 Views Asked by At

I want to make a program which takes photos, but every time I run the code it replaces the old image with the new one. This is because the file name is always the same.

Is it possible to make the program change a file name every time I run the program? So that the code makes a new file name automatically for every time I run the code.

the code I have for now

4

There are 4 best solutions below

0
Audemed On

You can generate a new and unique filename by adding a unique prefix when saving the file.

import uuid

unique_filename = uuid.uuid4().hex+".jpg"

Use this unique_filename instead of hardcoding the filename in your code in the camera.capture line

2
MilesMorales314 On

You can use Date and time to always get a unique filename.

import datetime, time, PiCamera

d = datetime.datetime.utcnow()
t = int(time.mktime(d.timetuple())) # or use t = time.time() or time.time_ns()

save_dir = "path/to/saving/directory"
file_loc = f"${save_dir}/save[${t}].jpg"

camera = PiCamera()

# your camera configurations

camera.capture(file_loc)
camera.stop_preview()
0
Friedrich On

You can check if a given file name already exists with the os.path.exists() function and make up a new one in case of a collision.

A tiny function to come up with new file names with incrementing numbers appended might look like this:

import os
import re

def incremental_filename(filename):
    while os.path.exists(filename):
        trunk, ext = os.path.splitext(filename)
        match = re.search(r'_\d*$', trunk)
        if match:
            i = int(match.group(0)[1:])
            filename = f'{trunk[:match.start()]}_{i+1}{ext}'
        else:
            filename = f'{trunk}_1{ext}'
    return filename

You can use it like this:

new_pic = incremental_filename('/home/amaliako/PIPPI/Kamera/Bilder/test.jpg')
camera.capture(new_pic)
0
Mark Setchell On

Here's a way to save the photo with a timestamp, and very usefully, also create a symbolic link from "latest.jpg" to that newest image so it's simple to always view the newest one - just like raspistill used to.

#!/usr/bin/env python3
from datetime import datetime
import os

<<< TAKE PICTURE WITH YOUR CODE >>>

# Get current time and form filename from it
now = datetime.now()
filename = f'{now}.jpg'

<<< Save picture using "filename" >>>

# Remove file "latest" if it exists and recreate as symlink to this new image
try:
    os.unlink('latest.jpg')
except:
    pass

os.symlink(filename, 'latest.jpg')

Here's how it looks after a few runs:

-rw-r--r--  1 mobile  mobile         0 Feb 16 01:11 2024-02-16 01:11:11.665823.jpg
-rw-r--r--  1 mobile  mobile         0 Feb 16 01:11 2024-02-16 01:11:24.675534.jpg
-rw-r--r--  1 mobile  mobile         0 Feb 16 01:11 2024-02-16 01:11:52.377710.jpg
lrwxr-xr-x  1 mobile  mobile        30 Feb 16 01:11 latest.jpg -> 2024-02-16 01:11:52.377710