Skip to main content

Use Python to add a file's modification time to the front of the file name

# Add a file's modified time to the front of the name of the file in the format

# YYYY-MM-DD-<original-filenam>.

#

# Works for files in the current directory.


from os import listdir

from os.path import isfile, join

import os

import time


mypath = "."

onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]


for file in onlyfiles:

  newname = time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(file))) + file

  print("Renaming file: " + file + " to: " newname)

  os.rename(file, time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(file))) + file)

Comments