How to save file without overwriting the previous python?

Asked

Viewed 243 times

-1

Hello, I am trying to save the name of the video files differently every time the program runs. currently it overwrites the name of the previous video.

This is my current code:

import cv2
print("MODO DE VIDEO COM 2 CAMERAS")

#NUMERO DE CAMERAS
webcam1 = cv2.VideoCapture(0)
webcam2 = cv2.VideoCapture(1)

#VERIFICANDO AS CAMERAS
if (webcam1.isOpened() == False):
    print("Camera 1 não conectada!")
if (webcam2.isOpened() == False):
    print("Camera 2 não conectada!")   

#ARMAZENAMENTO
nome1=("Video_camera1.avi")
nome2=("Video_camera1.avi")
fourcc1 = cv2.VideoWriter_fourcc(*"DIVX")
fourcc2 = cv2.VideoWriter_fourcc(*'DIVX')
file1 = cv2.VideoWriter(nome1,fourcc1, 10.0,(640,480))
file2 = cv2.VideoWriter(nome2,fourcc2, 10.0,(640,480))

while (True):
    ret, frame1 = webcam1.read()
    ret, frame2 = webcam2.read()

    if ret==True:
        file1.write(frame1)
        file2.write(frame2)

        cv2.imshow('Webcam1 1',frame1)
        cv2.imshow('Webcam1 2',frame2)
        if cv2.waitKey(1) == ord('s'):

            break
    else:
        break
print("FINALIZADO")
webcam1.release()
webcam2.release()
file1.release()
file2.release()
cv2.destroyAllWindows()
  • 2

    Simply change the values of nome1 and nome2 which, apparently, will be the names of the archives.

3 answers

1


As @Anderson Carlos Woss commented above you just need to change nome1 and nome2, but if you don’t always want to open the code and change it every time you run or if you want to let the user choose, consider doing something like this:

n1 = input("Digite o nome do primeiro arquivo: ")
n2 = input("Digite o nome do segundo arquivo: ")

nome1=(f"{n1}.avi")
nome2=(f"{n2}.avi")

And consider including something to change the name if a file already exists with the typed text:

import os.path
if os.path.isfile(f"seu_diretorio/{nome1}"): #seu_diretorio é o diretório onde 
#você vai gravar os arquivos
    n1 = input(f"Um arquivo com o nome {nome1} já existe. Por favor, digite outro nome: ")
    nome1=(f"{n1}.avi")
if os.path.isfile(f"seu_diretorio/{nome2}"):
    n2 = input(f"Um arquivo com o nome {nome2} já existe. Por favor, digite outro nome: ")
    nome2=(f"{n2}.avi")

If you want to save without asking the user, consider doing something like this:

import os           
import glob
n = int([os.path.basename(x) for x in glob.glob("seu_diretorio/*.txt")][-1][8:9])
n1 = n + 1
n2 = n1 + 1

nome1=(f"camera1_{n1}.avi")
nome2=(f"camera2_{n2}.avi")

Note: In this last example I considered the files with name following the default: camera1_0.avi, camera1_1.avi, camera1_2.avi..

  • I would like to save without asking the user. Just incrementing some number at the end. Type camera1_001, camera1_002, camera1_00 etc

  • I edited the answer.

0

You are passing the same name to the files in the variables nome1 and nome2, so it’s overwriting.

Try to change that way:

#ARMAZENAMENTO
nome1=("Video_camera1.avi")
nome2=("Video_camera2.avi")

0

To stay in a more dynamic and organized way, you can put the date and time in the file name, for example

from datetime import datetime

data = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
nome1 = "video_camera1_{}.avi".format(data)
nome2 = "video_camera2_{}.avi".format(data)

The result will be video_camera1_2019-07-01_14-38-12.avi and video_camera2_2019-07-01_14-38-12.avi

so the names of the videos will always be different, and will no longer overwrite the old ones, and gets organized, you know which files is from what date and time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.