简体   繁体   中英

How to rename a file in python

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

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)

Try

import os
import time

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

os.rename('3214.xlsx', f'3214_{current_milli_time}.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM