-1

Let's say I'm uploading

Desktop/folder/dog.jpg, Desktop/folder/fish.jpg, Desktop/folder/lizard.jpg

Could I theoretically do something like

a = ['Desktop/folder/dog.jpg', 'Desktop/folder/fish.jpg', 'Desktop/folder/lizard.jpg']

for x in a
    b = read(x)
    regex(x)= b

so that without doing each one manually, it ends up like

dog=read(dog.jpg)
fish=read(fish.jpg)
lizard=read(lizard.jpg)

?

litmuz
  • 71
  • 8
  • I don't understand what you're trying to do, particularly where your pseudocode assigns something to a function call. – TigerhawkT3 Jan 02 '17 at 05:12
  • You can refer the answer http://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name which is similar to what you want – Joshi Sravan Kumar Jan 02 '17 at 05:19

1 Answers1

1

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353