2

I read in some posts and documentations that you can change to relative paths in python with os.path.expanduser(~/.PATHNAME). I struggle with using it at the moment. When I use it, I end up one directory above the destined path.

from django.shortcuts import render
import os
import subprocess

def index(request):
  os.path.expanduser('~/.usernames')
  files = []
  for file in os.listdir("."):
    files.append(file)
  return render(request, 'sslcert/index.html', dict(files = files))
2
  • which print statement gives you the wrong path? is it the os.path.expanduser? or the os.listdir(".") ? Commented Nov 8, 2013 at 15:37
  • both ! and I am really confused about that. When I used os.chdir and I used the absolute path, which I wanted to get rid of, it worked. Commented Nov 8, 2013 at 15:40

1 Answer 1

4

It looks like you're missing a step, and that you intend to go into the directory, like this:

os.chdir(os.path.expanduser('~/.usernames'))

Otherwise your os.path.expanduser line is just generating a path that is used for nothing.

Sign up to request clarification or add additional context in comments.

5 Comments

That's what it is supposed to do. What do you want to do?
okay my aim is to change the directory from a certain location. The location my python script is in. I thought I could change the directory like this: "LOCATION_WHERE_I_AM_AT" (the location my python script is as well) (-->change to the subdirectory -->) "usernames". I think I understood os.path.expanduser wrong :( sorry
So you want to get a list of files in a directory? Is it always the same, or does it depend on the username of the person running the script? If it is always the same, you should probably hardcode it. If it is relative to the user, then you probably do need os.path.expanduser.
you got it ^^ I might have written that in my question too.. didn't know it was important. I wanted to get a list of the files in this directory ! aaand its relative to the user as well <-- important edit
So if the directory is /home/myusername/directory you can just use os.listdir(os.path.expanduser('~/directory'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.