简体   繁体   中英

How do i rename a file if it already exists in python

I searched online but found nothing really helpful. I am trying to verify a file name. If that file name already exists, change the name slightly. For instance. Writing a file User.1.1.jpg . I want it to change to User.2.1.jpg if 1.1 already exists and so on.

import cv2
import os
cam = cv2.VideoCapture(0)
cam.set(3, 640)
cam.set(4, 480)
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#face_id = input('\n id: ')
print("\n [INFO] Initializing face capture. Look the camera and wait ...")
count = 1
face_id = 1
while(True):
    ret, img = cam.read()
    img = cv2.flip(img, 1)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
        count += 1
        if os.path.exists("dataset/User.%s.1.jpg" % face_id):
            face_id + 1
        cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
        cv2.imshow('image', img)
    k = cv2.waitKey(100) & 0xff
    if k == 27:
        break
    elif count >= 30:
         break
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()

You can use a while loop instead of an if statement to keep incrementing face_id until the target file name is found to be available.

Change:

if os.path.exists("dataset/User.%s.1.jpg" % face_id):
    face_id + 1

to:

while os.path.exists("dataset/User.%s.1.jpg" % face_id):
    face_id += 1

Here is a function I made to add an incrementing number to the end of the existing file name. You would only need to change the string manipulation depending on your desired new file name formatting.

def uniq_file_maker(file: str) -> str:
    """Create a unique file path"""
    # get file name and extension
    filename, filext = os.path.splitext(os.path.basename(file))
    # get file directory path
    directory = os.path.dirname(file)
    # get file without extension only
    filexx = str(directory + os.sep + filename)
    # check if file exists
    if Path(file).exists():
        # create incrementing variable
        i = 1
        # determine incremented filename
        while os.path.exists(f"{filexx} ({str(i)}){filext}"):
            # update the incrementing variable
            i += 1
        # update file name with incremented variable
        filename = directory + os.sep + filename + ' (' + str(i) + ')' + filext
    return filename

Additionally, here is a similar function I made that does the same thing when creating a new directory.

def uniq_dir_maker(directoryname: str) -> str:
    """Create a unique directory at destination"""
    # file destination select dialogue
    Tk().withdraw()  # prevent root window
    # open file explorer folder select window
    dirspath = filedialog.askdirectory(title='Select the output file save destination')
    # correct directory file path
    dirsavepath = str(dirspath + os.sep + directoryname)
    # try to create directory
    try:
        # create directory at destination without overwriting
        Path(dirsavepath).mkdir(parents=True, exist_ok=False)
    # if directory already exists add incremental integers until unique
    except FileExistsError:
        # create incrementing variable
        i = 1
        # determine incremented filename
        while os.path.exists(f"{dirsavepath} ({str(i)})"):
            i += 1
        # update directory path with incremented variable
        dirsavepath = dirsavepath + ' (' + str(i) + ')'
        # create now unique directory
        Path(dirsavepath).mkdir(parents=True, exist_ok=False)
    # add os separator to new directory for saving
    savepath = dirsavepath + os.sep
    return savepath

If you want to use pathlib library with adding suffix of datetime then it would be like that:

from pathlib import Path
from datetime import datetime

# path and file parameters
path = Path('/home/') #path to your files  
file_name = 'file.txt' # your filename here

#
filename_full = path.joinpath(file_name)  
if filename_full.is_file(): #checks whether the file of this name already exists
      suffix = datetime.now().strftime("%Y%m%d_%H%M%S") #creates suffix with current date and exact time
      print('The file exists. Im adding datetime {suffix} to filename')
      file_name1 = filename_full.stem + suffix #adds suffix to filename
      filename_full = path.joinpath(file_name1).with_suffix('.txt') #create full filename with path and the final suffix
      print(filename_full)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM