Steve Steve - 2 months ago 31
Python Question

python/psychopy: for loop to split image names

I have a list of images and I want to split their names at the '=' symbol.

e.g. from:

'set_one-C:\Users\Documents\stim\01=aa.png'


to

'aa.png'


I have tried to create a 'for loop' to run through each item in the list and split the names in turn. Despite no error in the console, the names don't appear to be split.

Here is my code and loop:

imgList1 = glob.glob(os.path.join('C:\Users\Documents\stim','*.png'))

set_one = [visual.ImageStim(win, img, name='set_one-' + img) for img in imgList1[:8]]
set_two = [visual.ImageStim(win, img, name='set_two-' + img) for img in imgList1[8:16]]

sets = [set_one, set_two]

a1 = sets[0][0]
a2 = sets[0][1]
a3 = sets[0][2]
a4 = sets[0][3]
a5 = sets[0][4]
a6 = sets[0][5]
a7 = sets[0][6]
a8 = sets[0][7]

list = [a1,a2,a3,a4,a5,a6,a7,a8]

print a1

for item in list:

item = item.name.split('=')[1]

print a1

>>ImageStim(autoLog=True, color=array([ 1., 1., 1.]), colorSpace='rgb', contrast=1.0, depth=0, flipHoriz=False, flipVert=False, image=str(...), interpolate=False, mask=None, maskParams=None, name=str(...), opacity=1.0, ori=0.0, pos=array([ 0., 0.]), size=array([ 18.36534845, 11.47834278]), texRes=128, units='deg', win=Window(...))
>>ImageStim(autoLog=True, color=array([ 1., 1., 1.]), colorSpace='rgb', contrast=1.0, depth=0, flipHoriz=False, flipVert=False, image=str(...), interpolate=False, mask=None, maskParams=None, name=str(...), opacity=1.0, ori=0.0, pos=array([ 0., 0.]), size=array([ 18.36534845, 11.47834278]), texRes=128, units='deg', win=Window(...))


I know I could simply split them individually like this:

a1 = a1.name.split('=')[1]
a2 = a2.name.split('=')[1] etc..

print a1

>>aa.png


But I do need to automate this due to the amount of splitting that I need to do. I'm unsure as to why the for loop does not split the names of each image from the list.

Thanks,
Steve

Answer
item = item.name.split('=')[1] 

This doesn't work.... You want this instead:

new_list = []
for item in list:
    new_list.append(item.name.split('=')[1])

print(new_list)

Since you aren't changing your list in the for loop. You are only changing the item, but you aren't editing it in the list, if that make sense.

Another way around this is the following:

for i, item in enumerate(list):
    list[i] = item.name.split('=')[1]
Comments