I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.
Any help would be greatly appreciated.
To get the current datetime use:
import datetime
dt = str(datetime.datetime.now())
Then to rename file:
import os
newname = 'file_'+dt+'.txt'
os.rename('text.txt', newname)
import os
import datetime
src = '/home/thewoo/text.txt'
dst = '/home/thewoo/%s-text.txt' % datetime.datetime.now()
os.rename(src, dst)
Modify dst
and strftime the date as required.
import os
import date
timestamp = datetime.datetime.now()
t = timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second
split_filename = filename.split('.')
os.rename(filename, split_filename[:-1] + '_' + '-'.join(t))
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.