I’m trying to change the numbering of items in a list with python but it seems to be put into numerical order no matter what I do.
Say I have the following items in a list called items
items = ['1. item1', '2. item2', '3. item3', '4. item4']
It’s easier to visualize like this, so here is the current order
1. item1
2. item2
3. item3
4. item4
From another function I rearrange the order to be:
3. item3
1. item1
4. item4
2. item2
Now, the function that I’m having trouble with simply renames the files to correspond with their position, so it will now be:
1. item3
2. item1
3. item4
4. item2
The problem is that the numbers are placed back into numerical order. My list items is in a specific order, and I want the items to be numbered according to their position in the list
def order(self, directory):
i = 1
#print self.files
for filename in os.listdir(directory):
if filename in self.files: #if the current file in the directory is part of the files list
newfile = re.sub(r'^[0-9][.]',"",filename) #remove the number and decimal from the beginning
os.rename(directory + "/" + filename, directory + "/" + str(i) + ". " + newfile) #rename it with a new number and decimal
i = i + 1
#print newfile
Try to use instead
i– index of the item in the listBecause I am not sure how
os.listdirmake order of the files.