【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)
相关推荐
一条上岸小咸鱼3 分钟前
Kotlin 基本数据类型(五):Array
android·前端·kotlin
大明886 分钟前
用 mouseover/mouseout 事件代理模拟 mouseenter/mouseleave
前端·javascript
小杨梅君8 分钟前
vue3+vite中使用自定义element-plus主题配置
前端·element
关山12 分钟前
MCP实战
python·ai编程·mcp
一个专注api接口开发的小白13 分钟前
Python + 淘宝 API 开发:自动化采集商品数据的完整流程
前端·数据挖掘·api
林太白13 分钟前
Nuxt.js搭建一个官网如何简单
前端·javascript·后端
晴空雨14 分钟前
一个符号让 indexOf 判断更优雅!JavaScript 位运算的隐藏技巧
前端·javascript
摸着石头过河的石头14 分钟前
前端调试全攻略:从PC到移动端的一站式实战指南
前端·debug
小猪猪屁16 分钟前
🚀 用 Nuxt3 打造公司官网:一场从 0 到 1 的实战冒险
前端
悠哉悠哉愿意29 分钟前
【Python语法基础学习笔记】if语句
笔记·python·学习