Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lists Beginner

I created a list in Python:

mylist=os.listdir("/User/Me/Folder")

now I have a list of files in a List.

What I would like to do is:

Take one file name after the other and add a URL to it:

/myurl/ + each item in mylist

And then I would like to write the result in a html template from Django.

So that it display all the images in that folder in a list of html

How can I achieve this?

Thanks

like image 611
MacPython Avatar asked Feb 27 '23 15:02

MacPython


1 Answers

Using list comprehensions, you can transform your original list, "mylist", into a list with the URL prefix like so:

urllist = ['/myurl/%s' % the_file for the_file in mylist]

Analysis:

a) the expression in the square brackets is the list comprehension. it says: iterate over each item in "mylist", temporarily calling the iterated item "the_file" and transform it using the subexpression: '/myurl/%s' % the_file

b) the transformation expression says, create a string where %s is replaced by the string represented by the value of "the_file"

like image 53
Joubert Nel Avatar answered Mar 04 '23 10:03

Joubert Nel