Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Code challenge - Python for Filesystems

Hey All,

I believe that I am close to solving the code challenge, but keep getting an error.

It works in my local environment. Any assistance would be greatly appreciated,

Rod

def absolute (path, root):
    # If the path is not already absolute, return the path with the root prepended to it.
    # For example: absolute("projects/python_basics/", "/") would 
    # return "/projects/python_basics/" while 
    # absolute("/home/kenneth/django", "C:\") would return "/home/kenneth/django".

    # Check to see if the path begins with the same character as the absolute
    # If no, then pre-apprend the path with the absolute value

    if (path.startswith(root)):
        return path
    elif (root == "C:\\"):
        return path
    else:
        path = root + path
    return path
Josh Keenan
Josh Keenan
19,529 Points

can you link to the challenge?

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 27,816 Points

Rod,

This question is a little strange and I got stuck on it too. My solution is classical python interpretation-- NOTE THIS DOES NOT WORK (but should). I interpret absolute path to be a path that begins with a "slash" or drive letter (e.g. C:\ for Windows systems). To me, if you're going to import "os" library, you should take advantage of its features os.path.isabs() and os.path.join()

import os

def absolute(path, root):
    # check if path_str is absolute
    if os.path.isabs(path):
        return path
    # return joined path
    return os.path.join(root, path)

But a Treehouse insider gave me a hint that will help you pass it. At some point, I will see if Treehouse (or maybe I can volunteer) to rewrite the question wording and tests!!

Note that the code below passes, but doesn't actually conform to the description. And also doesn't use the "os" library which was imported. :-(

TREEHOUSE HINT: if '/home' is not in the path string, return the conjoined root and path.

--SPOILER BELOW--

import os

def absolute(path, root):
    if '/home' not in path:
        return root + path
    else:
        return path