根据创建的时间+d重命名文件

2024-03-28 03:07:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习Python并试图理解下面的代码有什么问题。你知道吗

出于测试目的,我想将50个图像重命名为Hour.Minute.Second_Year_Month_Day.jpg。下面的代码执行,但我得到的是文件名的当前时间和日期,而不是图像的创建日期。你知道吗

我错过了什么?我读到getctime适用于Windows和Mac birthtime,或者我在胡说八道(既然我在Mac上,就提起这个问题)?你知道吗


directory = './'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( file )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension; 

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index; 
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0; 

        os.rename( file, newfile );
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )


print( 'All done. ' + str(count) + ' files are renamed. ')

Tags: in图像formatstringindextimeosmac
2条回答

已纠正代码:-

import os
import datetime

directory = r'Dir_path'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( os.path.join(directory, file) )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( os.path.join(directory, file), os.path.join(directory, newfile))
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )


print( 'All done. ' + str(count) + ' files are renamed. ')

您的代码运行在Windows操作系统中很好,只是做了一些改进,添加了os.path.join(),使其在处理文件时更加灵活。如果你在Mac上,那么试着用os.stat(file).st_birthtime而不是os.path.getctime()。你知道吗

建议IMP漫游:-

  • 您使用的时间戳结构不是最好的,因为 时间戳通常按持续时间降序排列 i、 e年>;月>;日>;时>;分>;秒。此时间戳 通常使用标准(ISO 8601)。你知道吗
  • 您应该通过lower()传递文件的扩展名以使 扩展名全部小写。因为你的代码将无法处理图像 扩展名为.JPG.PNG的文件。你知道吗

在MacOS下,您应该尝试st_birthtime

os.stat(file).st_birthtime

请注意,您当前的代码在Windows上正常工作。你知道吗

相关问题 更多 >