<p><strong>已纠正代码:-</strong></p>
<pre><code>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. ')
</code></pre>
<p>您的代码运行在Windows操作系统中很好,只是做了一些改进,添加了<code>os.path.join()</code>,使其在处理文件时更加灵活。如果你在Mac上,那么试着用<code>os.stat(file).st_birthtime</code>而不是<code>os.path.getctime()</code>。你知道吗</p>
<p><strong>建议IMP漫游:-</strong></p>
<ul>
<li>您使用的时间戳结构不是最好的,因为
时间戳通常按持续时间降序排列
i、 e年>;月>;日>;时>;分>;秒。此时间戳
通常使用标准<strong>(ISO 8601)</strong>。你知道吗</li>
<li>您应该通过<code>lower()</code>传递文件的扩展名以使
扩展名全部小写。因为你的代码将无法处理图像
扩展名为<code>.JPG</code>或<code>.PNG</code>的文件。你知道吗</li>
</ul>