【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)
相关推荐
followYouself2 分钟前
ViewPager+Fragment
android·前端
37方寸4 分钟前
前端基础知识(HTML、CSS)
前端·css·html
xj7573065338 分钟前
Django 面试常见问题
python·面试·django
u1301309 分钟前
深入解析二维码技术与前端生成方案
前端·二维码
a努力。9 分钟前
得物Java面试被问:Netty的ByteBuf引用计数和内存释放
java·开发语言·分布式·python·面试·职场和发展
小范馆20 分钟前
STM32F03C8T6通过AT指令获取天气API-下篇
前端·stm32·esp8266-01s
开开心心_Every26 分钟前
无广告输入法推荐:内置丰富词库免费皮肤
服务器·前端·学习·决策树·edge·powerpoint·动态规划
卓怡学长1 小时前
m111基于MVC的舞蹈网站的设计与实现
java·前端·数据库·spring boot·spring·mvc
写代码的【黑咖啡】1 小时前
Python中的JSON处理(标准库)
开发语言·python·json
C_心欲无痕6 小时前
前端实现水印的两种方式:SVG 与 Canvas
前端·安全·水印