Automatically get the date created and rename the file to it

Viewed 100

I was wondering if there was a way to automatically get the date created and rename the file to it. I was coding in it a bit, but then I got an error. The error said FileNotFoundError: [WinError 2] The system cannot find the file specified: 'AutoDateRename'. Where AutoDateRename is the name of the folder I want the renamed files to go into. Is there a way to do this? The Full Error is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\lucio\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:/Users/lucio/Documents/PythonWorkspace/FileAutoDateRename/script.py", line 21, in RenameDateCreated
    os.rename(rf'{E1_Val.get()}/{filename}',rf'{E1_Val.get()}/AutoDateRename/{time.ctime(os.path.getctime(filename))}')
  File "C:\Users\lucio\AppData\Local\Programs\Python\Python38-32\lib\genericpath.py", line 65, in getctime
    return os.stat(filename).st_ctime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'AutoDateRename'

My Code:

from tkinter import *
from tkinter import filedialog
import os.path, time
import os

window = Tk()
window.title("File Auto Date Rename")
window.geometry("500x300")
window.resizable(width=False,height=False)

E1_Val = StringVar()

def SelectFolder():
    window.filename = filedialog.askdirectory()
    E1.delete(0,"end")
    E1.insert(END,window.filename)

def RenameDateCreated():
    os.mkdir(f'{E1_Val.get()}/AutoDateRename')
    for filename in os.listdir(E1_Val.get()):
        os.rename(rf'{E1_Val.get()}/{filename}',rf'{E1_Val.get()}/AutoDateRename/{time.ctime(os.path.getctime(filename))}')

L1 = Label(text="Auto Date Rename",font='Helvetica 16 bold underline')
L1.pack()

L2 = Label(text="Folder Path",font='Helvetica 12 bold italic')
L2.pack(pady=5)

E1 = Entry(window,textvariable=E1_Val)
E1.pack(pady=5)

B1 = Button(window,text="Locate",height=1,width=5,command=SelectFolder)
B1.pack(pady=5)

L4 = Label(text="Rename Options",font='Helvetica 12 bold italic')
L4.pack(pady=5)

B2 = Button(window,text="Rename Using Date Created",height=1,width=25,command=RenameDateCreated)
B2.pack(pady=2)

B3 = Button(window,text="Rename Using Date Modified",height=1,width=25)
B3.pack(pady=2)

L5 = Label(text="Make sure that the folder you\nare converting is backed up in a safe location!",font='Helvetica 14 bold')
L5.pack(pady=15)

window.mainloop()
1 Answers

Since you created a directory AutoDateRename inside the source directory (returned by E1_Val.get(), it will be included in the list returned by os.listdir() and I think you don't want to rename it. So you should check whether the source file is a file and not a directory.

And os.path.getctime(filename) should be os.path.getctime(os.path.join(E1_Val.get(), filename)) instead.

Also time.ctime() may return string with characters (like :) that are not allowed in filename. Use time.strftime() to format the time to be a valid filename.

Below is an updated RenameDateCreated():

def RenameDateCreated():
    srcdir = E1_Val.get().strip()
    if srcdir:
        destdir = os.path.join(srcdir, 'AutoDateRename') 
        os.makedirs(destdir, exist_ok=True) # create the directory if it does not exists
        for filename in os.listdir(srcdir):
            srcpath = os.path.join(srcdir, filename)
            if os.path.isfile(srcpath): # only process file, not directory
                ctime = time.strftime('%Y%m%d_%H%M%S', time.localtime(os.path.getctime(srcpath)))
                destpath = os.path.join(destdir, f'{ctime}_{filename}')
                os.rename(srcpath, destpath)
Related