简体   繁体   English

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

[英]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 .写一个文件User.1.1.jpg I want it to change to User.2.1.jpg if 1.1 already exists and so on.如果1.1已经存在,我希望它更改为User.2.1.jpg等等。

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. 您可以使用while循环而不是if语句来使face_id递增,直到找到目标文件名为止。

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.这是一个 function,我在现有文件名的末尾添加了一个递增的数字。 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.此外,这是我制作的一个类似的 function,它在创建新目录时做同样的事情。

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:如果你想使用 pathlib 库并添加 datetime 的后缀,那么它将是这样的:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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