I have roughly 80 files in that files all files have # number like (in file name's last portion has #1,#2,#3 like) I want to sort this with # order how can I do that.
Please see image for more understanding:
1 Answer
I have written and tested this code which seems to get the job done for me.
All this does is gets the number at the end of each file name and appends it to the beginning so that your file explorer gives priority to this number while sorting.
Modify variables x,y and dir per your requirement.
If your file name is in the format
sample01.txt
Setting y = 4 will skip 4 characters from the end (.txt)
x = 2 will fetch 2 characters after skipping over y characters (01)
These two characters will be appended to the beginning of your file name changing it to
01sample.txt
import os
y = 4 #number of characters to skip over from the end of file name
x = 2 #number of characters to copy after skipping y characters
dir = "/home/John/test" #location of your files
n = -y-x
m = -y
for filename in os.listdir(dir): filename = os.path.basename(filename) num = filename[n:m] #fetch number from the end of the name new_name = num+filename #append number to the beginning #new_name = new_name[-(len(filename)+1):n] +new_name[m:] #optional line to delete number at the end of the filename old_file = os.path.join(dir, filename) new_file = os.path.join(dir, new_name) os.rename(old_file,new_file) print(new_name)NOTE:
- This modifies the names of all files in the directory, so make sure there aren't any files in the folder you wouldn't want to modify.
- I highly recommend you make a copy of your folder and test it out to detect any inconsistencies, if any.