【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)
相关推荐
ConardLi12 小时前
把 Claude Design 做成 Skill,你的网站也能拥有顶级视觉体验
前端·人工智能·后端
星越华夏12 小时前
python——三角函数用法
开发语言·python
We་ct13 小时前
LeetCode 120. 三角形最小路径和:动态规划详解
前端·javascript·算法·leetcode·typescript·动态规划
gmaajt13 小时前
mysql如何检查数据库表是否存在损坏_使用CHECK TABLE命令修复
jvm·数据库·python
IT_陈寒13 小时前
React状态更新那点事儿,我掉坑里爬了半天
前端·人工智能·后端
cwxcc13 小时前
Google Core Web Vitals(核心网页指标)
前端·性能优化
heRs BART13 小时前
【Flask】四、flask连接并操作数据库
数据库·python·flask
|晴 天|14 小时前
Vue 3 + LocalStorage 实现博客游戏化系统:成就墙、每日签到、积分商城
前端·vue.js·游戏
PyHaVolask14 小时前
Python 爬虫进阶:直接请求 JSON 接口与开发者工具使用
爬虫·python·请求头·反爬·json接口·chrome开发者工具
larance14 小时前
安装dify的几个问题
python