0

I am getting all file names under directory dir:

files = os.listdir(dir)

and after rendering file names to template, i am showing them in template like this:

{% for each in files %}
<li>
  <a href="{{each}}" target="_blank">{{each}}</a>
<li>
{% endfor %}

I want that If i click on filename, the file should be opened in new window. but here the problem is that files = os.listdir(dir) returns only file names and not its relative path. how do i get the path also?

5
  • can you send the path to the template in another variable? ... <a href="{{path}}/{{each}}" ... Commented Sep 17, 2013 at 17:55
  • Are you looking for os.getcwd()? Commented Sep 17, 2013 at 17:58
  • @jcfollower, how to get the path is my problem now. i am able to get absolute path with C://... but i need the relative path Commented Sep 17, 2013 at 18:11
  • Once you have the absolute path, can't you just use the last part of it as the relative path? Commented Sep 17, 2013 at 18:20
  • @jcfollower, absolutely! :D totally right. Commented Sep 17, 2013 at 18:24

1 Answer 1

1

Add a '/' to tell the browser to start from the site's root. Also, opening the link in a new window should be HTML:

<a href="/{{each}}" target="_blank">{{each}}</a>

Edit:

files = [os.path.join(dir, f) for f in files]
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, but {{each}} is filename, i need to get the path of those files, any idea?
@doniyor I added that to the response
Thanks, but this gives the absolute path, absolute path gives some errors in chrome etc... how can i get the relative path so that i can open it?
@doniyor relative to start_dir would be os.path.relpath(os.path.join(dir, f), start=start_dir)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.