Here's a function that extracts a name from a filename:
def getname(astr):
import os.path
name = os.path.basename(astr)
name = os.path.splitext(name)[0]
return name
From your list of filenames I can get a list of 'variable' names:
In [150]: filenames = ['Desktop/folder/dog.jpg', 'Desktop/folder/fish.jpg', 'Desktop/folder/lizard.jpg']
In [155]: [getname(i) for i in filenames]
Out[155]: ['dog', 'fish', 'lizard']
But rather than try to put them in the global name space, I'd suggest collecting them in a dictionary:
In [156]: adict = {getname(i): i for i in filenames}
In [157]: adict
Out[157]:
{'dog': 'Desktop/folder/dog.jpg',
'fish': 'Desktop/folder/fish.jpg',
'lizard': 'Desktop/folder/lizard.jpg'}
Or if with a read
function:
adict = {getname(i): read(i) for i in filenames}
Generally in Python it is more useful to collect objects, like these images, in a list or dictionary, rather than trying to assign each one to a separate variable.
It's nearly as easy to write adict['fish']
as it is fish
. With the dictionary you can easily 'loop' over the whole set
for k,v in adict.items():
print('name:',k)
display(v)
A comment links to a whole string of SO questions about assigning to variables, and why generally that is a poor idea.