开发者

Python os module path functions

开发者 https://www.devze.com 2023-02-03 12:38 出处:网络
From the documentation: os.path.realpath(path) Return the canonical path of the specified filename, eliminating any

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 n开发者_Python百科ot to test if files exist. My concern is to account for behaviour.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消