Reputation: 1
I have a lot of files in a specific directory and I want to rename all files with the extension type .txt after the file creation date and add a counter prefix. By the way, I'm using python on windows.
Example:
Lets say I have the files aaa.txt
, bbb.txt
, and ccc.txt
.
aaa.txt
is the newest file and ccc.txt
ist the oldest created file.
I want to rename the files that way:
999_aaa.txt, 998_bbb.txt, 997_ccc.txt ...
The counter should start with 999_newest file (I will never have more than 300 txt file). Like you can see I just want to give the newest file the highest number (sorted by creation date).
How would you do this?
Upvotes: 0
Views: 1290
Reputation: 32502
Have a look at this untested code:
import os
import glob
import shutil
# get a list of all txt files
fnames = glob.glob("*.txt")
# sort according to time of last modification/creation (os-dependent)
# reverse: newer files first
fnames.sort(key=lambda x: os.stat(x).st_ctime, reverse=True)
# rename files, choose pattern as you like
for i, fname in enumerate(fnames):
shutil.move(fname, "%03d_%s" % (999-i, fname))
For reference:
Upvotes: 2