0

From the documentation:

os.path.realpath(path)
Return the canonical path of the specified filename, eliminating any 
symbolic links encountered in the path (if they are supported by the 
operating system).

When I invoke this with an extant file's name, I get the path to it: /home/myhome/myproject.

When I invoke this with a 'nonsense.xxx' string argument, I still get a path to /home/myhome/myproject/nonsense.xxx. This is a little inconsistent because it looks like nonsense.xxx is taken to be a directory not a file (though it is neither: it does not exist).

When I invoke this with a null string file name, I still get a path to /home/myhome/myproject.

How can I account for this behaviour when the documentation says so little about realpath()? (I am using Python 2.5.)

Edit: Somebody suggested a way to test if files exist. My concern is not to test if files exist. My concern is to account for behaviour.

3 Answers 3

2

os.path isn't interested in whether or not the files exist. It is merely concerned with constructing paths.

realpath eliminates known symlinks from the equation, but directories that do not exist are assumed to be valid elements of a path regardless.

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

4 Comments

The os.path doc says: "This module implements some useful functions on pathnames". It does not say that os.path.realpath() will return a path regardless of any garbage you send it. However, that seems to be what it does.
@broiyan: Your expectations will cause you much more heartache if you assume the unstated.
a pathnames doesn't imply that it's a path to a file that exists. Just that it is a valid path.
@nate: well put. Broiyan, I would assume that it does things like check for loops in symlink paths, which are invalid.
2

Rather than guess, just read the code! It's there in your python installation. Or browse here, it's only 14 lines minus comments.

Comments

0

Place test such as "os.path.isfile(x)", "x is not None" and "os.path.isdir(x)" before the call?

Comments

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.