Dear Friends,
I have a sequence of two values as the following:

00001.doc
d:\pathtofile\image50.jpg

00002.doc
d:\pathtofile\image38.jpg

00003.doc
d:\pathtofile\image40.jpg

...

I would like to add the values to a list, sort the list by second value and rename the first value accordingly.
For example, the following steps:
Step 1
'00002.doc', 'd:\pathtofile\image38.jpg'
'00003.doc', 'd:\pathtofile\image40.jpg'
'00001.doc', 'd:\pathtofile\image50.jpg'

Step 2
'a00001.doc', 'd:\pathtofile\image38.jpg'
'a00002.doc', 'd:\pathtofile\image40.jpg'
'a00003.doc', 'd:\pathtofile\image50.jpg'

The pathtofile is always the same, so I will not need (probably) to break it and extract the filename.
Thank you for your help.
G.

This should get you partway there:

import os
import pprint

data_str = '''\
00001.doc
d:\pathtofile\image50.jpg

00002.doc
d:\pathtofile\image38.jpg

00003.doc
d:\pathtofile\image40.jpg
'''

data_list = []
temp_list = []
for ix, line in enumerate(data_str.split()):
    #print(line, len(temp_list), ix, ix%2)  # test
    if ix % 2 == 0:
        temp_list.append('a' + line)
    if ix % 2 == 1:
        folder, filename = os.path.split(line)
        temp_list.append(filename)
        data_list.append(temp_list)
        # reset temp_list
        temp_list = []

pprint.pprint(data_list)

print('-'*36)

# sort by second element (index = 1)
data_list_sorted = sorted(data_list, key = lambda x: x[1])

pprint.pprint(data_list_sorted)

''' my result -->
[['a00001.doc', 'image50.jpg'],
 ['a00002.doc', 'image38.jpg'],
 ['a00003.doc', 'image40.jpg']]
------------------------------
[['a00002.doc', 'image38.jpg'],
 ['a00003.doc', 'image40.jpg'],
 ['a00001.doc', 'image50.jpg']]
'''

For the rest send the list of lists through a loop again and sequentially rename/renumber the first elements.

If I understand this right, you want something like this ...

import pprint

mylist = [['a00002.doc', 'image38.jpg'],
['a00003.doc', 'image40.jpg'],
['a00001.doc', 'image50.jpg']]

newlist = []
for ix, item in enumerate(mylist):
    #print(item[0])  # testing
    item[0] = "a%05d.doc" % (ix+1)
    #print(item[0])  # testing
    newlist.append(item)

pprint.pprint(newlist)

''' result ...
[['a00001.doc', 'image38.jpg'],
 ['a00002.doc', 'image40.jpg'],
 ['a00003.doc', 'image50.jpg']]
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.