更改文件名至修改日期
问题描述:
我有以下问题,我写了一段代码,它重命名目录及其子目录中的文件名。现在,而不是将其更改为当前日期,我希望它更改为file modification date
。更改文件名至修改日期
我该怎么做?
import os, path
from datetime import datetime
import time
def walk_dir(path):
current_day = datetime.now().strftime("%Y-%m-%d")
for root, dirs, files in os.walk(path):
for filename in files:
current = root + "/" + filename
if os.path.isfile(current):
print "ORIGINAL NAME: " + current
ext = os.path.splitext(filename)[1]
target_name = os.path.join(root, '{}{}'.format(current_day, ext))
print "NEW NAME: " + target_name
os.rename(current, target_name)
walk_dir("/Users/shirin/Desktop/Artez")
答
import os
import datetime
for filename in directory:
modified_time = os.path.getmtime(filename) # get file modification timestamp
modified_date = datetime.date.fromtimestamp(modified_time) # convert timestamp to a date
os.rename(filename, modified_date.strftime("%Y-%m-%d"))
注意这是危险的,因为你可能会覆盖谁共享相同的修改日期的文件。
'new_file_name = datetime.datetime.now()。strftime('%y%m%d_%H%M%S')' –