【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)
相关推荐
ohMyGod_1231 小时前
React16,17,18,19新特性更新对比
前端·javascript·react.js
前端小趴菜051 小时前
React-forwardRef-useImperativeHandle
前端·vue.js·react.js
@大迁世界1 小时前
第1章 React组件开发基础
前端·javascript·react.js·前端框架·ecmascript
胖达不服输1 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
Hilaku1 小时前
从一个实战项目,看懂 `new DataTransfer()` 的三大妙用
前端·javascript·jquery
爱分享的程序员1 小时前
前端面试专栏-算法篇:20. 贪心算法与动态规划入门
前端·javascript·node.js
我想说一句1 小时前
事件委托与合成事件:前端性能优化的"偷懒"艺术
前端·javascript
吴佳浩1 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
爱泡脚的鸡腿1 小时前
Web第二次笔记
前端·javascript
良辰未晚1 小时前
Canvas 绘制模糊?那是你没搞懂 DPR!
前端·canvas