#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    103
    Rep Power
    3

    Convert Relative to Absolute Path


    Hello everyone,

    I am attempting to convert a relative file path to an absolute file path. I have input of path = 'text.txt'. I need to be able to determine the absolute path of 'c:/site/text.txt'.

    The os.path.abspath method doesn't work since it takes the current working directory path. os.path.realpath does the same thing. I've also tried changing the current working directory, but that doesn't really do anything unless I have the full path to begin with.

    I am doing this for a web server. I don't want users to have to enter the full path of the files they want to retrieve. Instead, I want to be able to navigate to the file manually if it exists.

    Cheers, Cam.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    4
    I'm not sure how you intend to find an absolute path from a relative path if you don't know what the path is relative to.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    103
    Rep Power
    3
    Originally Posted by Nyktos
    How can you find the full path to something if you don't know what directory it's in?
    Haha, that's my dilemma! I was hoping there was a way to do it.

    os.walk seems promising.
    http://docs.python.org/2/library/os.html
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    103
    Rep Power
    3
    Well, I didn't get an exact solution as to what I mentioned above. However, I did come up with a compromise. As long as the files are located in the root or sub directory of the root server, then this code will work.

    Code:
    def getAbsolutePath(path):
        scriptDir = os.getcwd();
        pathArr = [];
        for directory in path.split('/'):
            print directory;
            pathArr.append(directory);
        if '.' in pathArr[len(pathArr)-1]:
            del pathArr[len(pathArr)-1];
        path = '';
        for index in range(0,len(pathArr)):
            if pathArr[index] not in scriptDir:
                path = path + '/' + pathArr[index];
        return os.path.normpath(scriptDir + path);
    
    in main:
        abspath = getAbsolutePath(path);
        os.chdir(abspath);
    
    then I attach the filename and extension to it at a later time :)
    path = os.path.normpath(abspath + '/' + fileName + '.' + extension);
    I get the absolute path (file not included in path) and make that my working directory. That way I can just call the working directory to build the absolute path to the file.
    Last edited by Cameron0960; July 4th, 2013 at 11:26 PM.

IMN logo majestic logo threadwatch logo seochat tools logo