我刚刚开始学习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. ')
已纠正代码:-
您的代码运行在Windows操作系统中很好,只是做了一些改进,添加了
os.path.join()
,使其在处理文件时更加灵活。如果你在Mac上,那么试着用os.stat(file).st_birthtime
而不是os.path.getctime()
。你知道吗建议IMP漫游:-
lower()
传递文件的扩展名以使 扩展名全部小写。因为你的代码将无法处理图像 扩展名为.JPG
或.PNG
的文件。你知道吗在MacOS下,您应该尝试
st_birthtime
:请注意,您当前的代码在Windows上正常工作。你知道吗
相关问题 更多 >
编程相关推荐