【python】chrome浏览器,拖拽图片自动命名文件

chrome浏览器拖拽图片到本地文件夹,名字是乱的或者重名,那么我们将之前在本地的图片都命名好,就不会存在这个问题。

用python写一个程序,不断监测C:\Users\xjsd\Desktop\outpainting_test_data内的文件名(不算后缀),如果命名不满足f0001【0001是递增的】,就将该文件名改为满足规范的(后缀保持原样)。

python

python 复制代码
import os
import re
import time


def rename_files(directory_path):
    # Get a list of existing file names in the directory
    existing_files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]

    # Sort the existing file names
    existing_files.sort()

    # Initialize a counter for the new names
    counter = len(existing_files)

    # Iterate through existing files
    for filename in existing_files:
        base_name, file_extension = os.path.splitext(filename)

        # Define the expected pattern f0001
        pattern = re.compile(r'f(\d{4})')

        # Check if the current filename matches the pattern
        match = re.match(pattern, base_name)

        if not match:
            while 1:
                # If not, generate a new filename following the pattern
                new_filename = f'f{str(counter).zfill(4)}{file_extension}'

                # Update the counter
                counter += 1

                # Check if the new filename already exists
                if new_filename not in existing_files:
                    break

            # Rename the file
            old_file_path = os.path.join(directory_path, filename)
            new_file_path = os.path.join(directory_path, new_filename)
            os.rename(old_file_path, new_file_path)

            print(f'Renamed: {filename} -> {new_filename}')


# Replace 'C:\\Users\\xjsd\\Desktop\\outpainting_test_data' with your actual directory path
directory_path = r'C:\Users\xjsd\Desktop\outpainting_test_data'

while 1:
    # Run the rename_files function
    rename_files(directory_path)
    time.sleep(1)
相关推荐
我就是不信11 分钟前
Java8 lambda 表达式 forEach 如何提前终止?
开发语言·windows·python
A小码哥14 分钟前
大模型成本怎么降,5 个动作先做前两个
java·前端·spring
全栈弄潮儿18 分钟前
Python实战第9期:文件操作
后端·python·编程语言
小星星_ios23 分钟前
从 3Blue1Brown 到 NumPy:手写一个神经网络训练 MNIST
人工智能·python·神经网络
PHP是世界上最好的语言26 分钟前
ComPDF预览本地正常,部署后白屏:检查资源、路径和许可
前端
Maxwin26 分钟前
Manim 竖屏画布选 9×16 还是 4.5×8?从 font_size 和每单位像素数说起
python·ffmpeg
kiros_wang28 分钟前
项目分包方案:模块拆分、跨模块组件与方法引用规范
前端
PedroQue9930 分钟前
unix-utils v0.2.0 发布:modal 全端统一,自绘窗口解决输入框难题
前端·uni-app
Csvn31 分钟前
网络优化
前端
昭昭日月明33 分钟前
使用 Ragas 量化 RAG
python·langchain·ai编程