将文件名更改为修改日期

时间:2016-03-08 13:14:51

标签: python filenames

我有以下问题,我写了一段代码,在目录及其子目录中重命名文件名。现在,我希望将其更改为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")

1 个答案:

答案 0 :(得分:1)

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"))

注意这很危险,因为您可能会覆盖共享相同修改日期的文件。