【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)
相关推荐
振华OPPO36 分钟前
Vue:“onMounted“ is defined but never used no-unused-vars
前端·javascript·css·vue.js·前端框架
咚咚王者43 分钟前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
欧雷殿1 小时前
在富阳银湖成立地域化的软件研发团队
前端·程序员·创业
深蓝海拓1 小时前
使matplot显示支持中文和负号
开发语言·python
狂炫冰美式2 小时前
前端实时推送 & WebSocket 面试题(2026版)
前端·http·面试
AntBlack2 小时前
AI Agent : CrewAI 简单使用 + 尝试一下股票分析
后端·python·ai编程
JefferyXZF2 小时前
新手建站零门槛!Vercel+Cloudflare+Namesilo域名购买部署全流程
前端
一眼万里*e2 小时前
搭建本地deepseek大模型
python
1***Q7842 小时前
PyTorch图像分割实战,U-Net模型训练与部署
人工智能·pytorch·python
yinuo2 小时前
微信浏览器缓存机制大揭秘:为什么你总刷不出新页面?
前端