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"%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:

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

Leave a Comment