2016-03-08 196 views
1

我有以下問題,我寫了一段代碼,它重命名目錄及其子目錄中的文件名。現在,而不是將其更改爲當前日期,我希望它更改爲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") 
+0

'new_file_name = datetime.datetime.now()。strftime('%y%m%d_%H%M%S')' –

回答

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

注意這是危險的,因爲你可能會覆蓋誰共享相同的修改日期的文件。