How to rename a file in python

You can use os.rename as long as they are on the same filesystem. Otherwise, use shutil.move

To get the date you can use datetime.datetime.today().strftime("%Y_%m_%d_%H%M%S") and use the output of that in the new name of your file. (see how to use strftime here)

For example:

my_file="file_1.pdf"
file_name, file_extension = os.path.splitext(my_file)
date_str = datetime.datetime.today().strftime("%Y_%m_%d_%H%M%S")
os.rename(my_file, file_name + '_' + date_str + file_extension)

Leave a Comment