Python Starter List

I created a list in Python:

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

I now have a list of files in the list.

What I would like to do:

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

/ myurl / + each item in the list.

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

To display all the images in this folder in the html list

How can i achieve this?

thanks

+4
source share
3 answers

Using lists, you can convert the original "mylist" list to a list with a URL prefix as follows:

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

Analysis:

a) the expression in square brackets is an understanding of the list. he says: iterate over each element in "mylist", temporarily calling the iterated element "the_file" and transforming it using a subexpression: '/ myurl /% s'% the_file

b) the conversion expression says, create a line where% s is replaced by the line represented by the value "the_file"

+4
source
 {% for filename in listoffilenames %} /myurl/{{ filename }} {% endfor %} 
+3
source

For contrast, if you like to do this in a view (although there is no reason for this):

 mylist[:] = [url + x for x in mylist] 

If you do not need to modify the existing list, you can opt out of [:] .

+1
source

Source: https://habr.com/ru/post/1315913/


All Articles