如果文件已经存在于python中,我该如何重命名

时间:2018-09-25 11:53:25

标签: python loops

我在线搜索,但没有发现真正有用的东西。我正在尝试验证文件名。如果该文件名已经存在,请稍稍更改名称。例如。写入文件User.1.1.jpg。如果User.2.1.jpg已经存在,我希望将其更改为1.1,依此类推。

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()

2 个答案:

答案 0 :(得分:1)

您可以使用while循环而不是if语句来保持递增face_id直到发现目标文件名可用。

更改:

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

收件人:

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

答案 1 :(得分:0)

这是我在现有文件名末尾添加递增数字的函数。您只需要根据所需的新文件名格式更改字符串操作。

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

此外,这是我创建的一个类似函数,它在创建新目录时执行相同的操作。

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