Reputation: 18281
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
Upvotes: 4
Views: 216
Reputation: 3214
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"
Upvotes: 5
Reputation: 799130
For contrast, if you feel like doing this in the view (even though there's no good reason to do so):
mylist[:] = [url + x for x in mylist]
If you don't need to modify the existing list then you can drop the [:]
.
Upvotes: 1
Reputation: 799130
{% for filename in listoffilenames %}
/myurl/{{ filename }}
{% endfor %}
Upvotes: 3