【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)
相关推荐
等咸鱼的狸猫7 分钟前
# JS 核心六大主题:闭包内存模型、原型链查找、事件流机制与 Promise / Event Loop 实现视角复盘
前端·javascript
般若-波罗蜜20 分钟前
MinerU高级用法,避坑指南(持续更新)
人工智能·python·语言模型·自然语言处理
袋鱼不重41 分钟前
乐观锁与悲观锁:原理、选型与前后端实践
前端·后端
用户8356290780511 小时前
使用 Python 对 PDF 文档进行数字签名的方法
后端·python
Charonmomo1 小时前
react/antd - 不能正确打开标签页问题记录
前端·react.js·前端框架
李可以量化1 小时前
PTrade 量化入门必学:get\_trading\_day 交易日函数全解与实战(下)
python
柒和远方1 小时前
LeetCode 139. 单词拆分 —— 从暴力回溯到 DP 完全背包
javascript·python·算法
冬枳1 小时前
基于OpenSeagragon封装的前端病理切片展示组件
前端·typescript
半兽先生2 小时前
大模型实现金融文本分类
人工智能·python·金融
汤姆小白2 小时前
06-LoRA参数高效微调
人工智能·python·机器学习·transformer