-6

My requirement is to rename file and append with Current date.files will come with any format on runtime My input is like

1334.pdf
3214.xlsx
12_32.doc

My expected output

1334_2018238.pdf
3224_currentdate.xslx
Svickie7
  • 32
  • 8
  • 2
    Sounds great. Please let us know how it goes. If you need help, please show that you have done some research, attempted a solution yourself, and ask a specific question about the issue you are coming across. – dfundako Aug 23 '18 at 14:16
  • 4
    Possible duplicate of [How to rename a file using Python](https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python) – B001ᛦ Aug 23 '18 at 14:16
  • 1
    You should not be learning Python 2 in 2018. By the original timeline, it should be dead already (though it's now in terminal care on an extension for about a year and a half still). The recommended and supported version of the language is Python 3. – tripleee Aug 23 '18 at 14:17
  • That answer not suit my requirement – Svickie7 Aug 23 '18 at 14:18
  • @Svickie7 SO is not a 'do my work for me' kind of place. – dfundako Aug 23 '18 at 14:19

2 Answers2

2

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)
Austin Yates
  • 108
  • 9
1

Try

import os
import time

current_milli_time = lambda: int(round(time.time() * 1000))

os.rename('3214.xlsx', f'3214_{current_milli_time}.xlsx')
Bruck Wubete
  • 141
  • 2
  • 5