美文网首页
用ChatGPT4写代码修改照片文件名称

用ChatGPT4写代码修改照片文件名称

作者: 鄢中堡 | 来源:发表于2023-03-15 22:41 被阅读0次

花了两天时间终于弄到了GPT4,于是想测试一下编写代码的能力,发现顺利完成我给出的任务,特记录我发出的指令如下。

1:用python写一个函数,函数的参数为文件路径,遍历里面的jpg文件,读取extif中的拍摄日期,然后把文件改名成yyyyMMddhhmm.jpg格式,如果目标文件已经存在,在添加上随机的字母

2:添加代码输出执行的进度

3:我的文件夹有800多个文件,程序只处理了346个可能的原因是什么?

4:我给出的文件目录包含后缀为大写JPG的文件,是否没有处理?

5:添加代码,当日期找不到的时候,使用最后修改时间作为文件的命名时间

6:我需要在文件名中的日期后面,添加拍摄程序的前两个字母。

总结:6次要求是我看到代码后依次提出的。其间运行过几次代码,没有任何错误。如果我一次能写完整需求,估计他能一次写好。

完成的代码如下:


import os

import glob

import random

import string

from PIL import Image

from PIL.ExifTags import TAGS

from datetime import datetime

def rename_jpg_files(path):

    jpg_files = list(glob.glob(os.path.join(path, '*.jpg')))

    jpg_files.extend(glob.glob(os.path.join(path, '*.JPG')))  # Add uppercase .JPG files

    total_files = len(jpg_files)

    processed_files = 0

    for file in jpg_files:

        try:

            img = Image.open(file)

            exif_data = img._getexif()

            date_str = None

            make = ''

            if exif_data:

                date_tag = 36867  # 36867 is the tag ID for DateTimeOriginal

                make_tag = 271  # 271 is the tag ID for Make (Camera Manufacturer)

                if date_tag in exif_data:

                    date_str = exif_data[date_tag]

                if make_tag in exif_data:

                    make = exif_data[make_tag][:2]  # Get the first two letters of the make

            if date_str is None:

                last_modified_time = os.path.getmtime(file)

                date_str = datetime.fromtimestamp(last_modified_time).strftime('%Y%m%d%H%M%S')

            date_str = date_str.replace(':', '').replace(' ', '')

            new_name = f"{date_str}{make}.jpg"

            new_path = os.path.join(path, new_name)

            # Check if file with the new name already exists, if yes, append a random letter

            while os.path.exists(new_path):

                random_letter = random.choice(string.ascii_lowercase)

                new_name = f"{date_str}{make}{random_letter}.jpg"

                new_path = os.path.join(path, new_name)

            os.rename(file, new_path)

        except Exception as e:

            print(f"Error processing file {file}: {e}")

        processed_files += 1

        progress = (processed_files / total_files) * 100

        print(f"Progress: {processed_files}/{total_files} ({progress:.2f}%)")

# Example usage

folder_path = "path/to/your/folder"

rename_jpg_files(folder_path)

相关文章

网友评论

      本文标题:用ChatGPT4写代码修改照片文件名称

      本文链接:https://www.haomeiwen.com/subject/jwdrrdtx.html