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))
asked Nov 8, 2013 at 15:17
BoJack Horseman
4,46813 gold badges43 silver badges73 bronze badges
-
which print statement gives you the wrong path? is it the os.path.expanduser? or the os.listdir(".") ?usethedeathstar– usethedeathstar2013年11月08日 15:37:47 +00:00Commented 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.BoJack Horseman– BoJack Horseman2013年11月08日 15:40:37 +00:00Commented Nov 8, 2013 at 15:40
1 Answer 1
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
ratatoskr
That's what it is supposed to do. What do you want to do?
BoJack Horseman
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
ratatoskr
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.
BoJack Horseman
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
ratatoskr
So if the directory is /home/myusername/directory you can just use
os.listdir(os.path.expanduser('~/directory'))lang-py