Back to index

python3.2  3.2.2
Functions | Variables
posixpath Namespace Reference

Functions

def _get_sep
def normcase
def isabs
def join
def split
def splitext
def splitdrive
def basename
def dirname
def islink
def lexists
def samefile
def sameopenfile
def samestat
def ismount
def expanduser
def expandvars
def normpath
def abspath
def realpath
def _resolve_link
def relpath

Variables

list __all__
string curdir = '.'
string pardir = '..'
string extsep = '.'
string sep = '/'
string pathsep = ':'
string defpath = ':/bin:/usr/bin'
 altsep = None
string devnull = '/dev/null'
 _varprog = None
 _varprogb = None
tuple supports_unicode_filenames = (sys.platform == 'darwin')

Detailed Description

Common operations on Posix pathnames.

Instead of importing this module directly, import os and refer to
this module as os.path.  The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).

Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.

Function Documentation

def posixpath._get_sep (   path) [private]

Definition at line 38 of file posixpath.py.

00038 
00039 def _get_sep(path):
00040     if isinstance(path, bytes):
00041         return b'/'
00042     else:
00043         return '/'
00044 
00045 # Normalize the case of a pathname.  Trivial in Posix, string.lower on Mac.
00046 # On MS-DOS this may also turn slashes into backslashes; however, other
00047 # normalizations (such as optimizing '../' away) are not allowed
00048 # (another function should be defined to do that).

Here is the caller graph for this function:

def posixpath._resolve_link (   path) [private]
Internal helper function.  Takes a path and follows symlinks
until we either arrive at something that isn't a symlink, or
encounter a path we've seen before (meaning that there's a loop).

Definition at line 410 of file posixpath.py.

00410 
00411 def _resolve_link(path):
00412     """Internal helper function.  Takes a path and follows symlinks
00413     until we either arrive at something that isn't a symlink, or
00414     encounter a path we've seen before (meaning that there's a loop).
00415     """
00416     paths_seen = set()
00417     while islink(path):
00418         if path in paths_seen:
00419             # Already seen this path, so we must have a symlink loop
00420             return None
00421         paths_seen.add(path)
00422         # Resolve where the link points to
00423         resolved = os.readlink(path)
00424         if not isabs(resolved):
00425             dir = dirname(path)
00426             path = normpath(join(dir, resolved))
00427         else:
00428             path = normpath(resolved)
00429     return path

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.abspath (   path)
Return an absolute path.

Definition at line 367 of file posixpath.py.

00367 
00368 def abspath(path):
00369     """Return an absolute path."""
00370     if not isabs(path):
00371         if isinstance(path, bytes):
00372             cwd = os.getcwdb()
00373         else:
00374             cwd = os.getcwd()
00375         path = join(cwd, path)
00376     return normpath(path)
00377 
00378 
00379 # Return a canonical path (i.e. the absolute location of a file on the
00380 # filesystem).

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.basename (   p)
Returns the final component of a pathname

Definition at line 129 of file posixpath.py.

00129 
00130 def basename(p):
00131     """Returns the final component of a pathname"""
00132     sep = _get_sep(p)
00133     i = p.rfind(sep) + 1
00134     return p[i:]
00135 
00136 
00137 # Return the head (dirname) part of a path, same as split(path)[0].

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.dirname (   p)
Returns the directory component of a pathname

Definition at line 138 of file posixpath.py.

00138 
00139 def dirname(p):
00140     """Returns the directory component of a pathname"""
00141     sep = _get_sep(p)
00142     i = p.rfind(sep) + 1
00143     head = p[:i]
00144     if head and head != sep*len(head):
00145         head = head.rstrip(sep)
00146     return head
00147 
00148 
00149 # Is a path a symbolic link?
00150 # This will always return false on systems where os.lstat doesn't exist.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.expanduser (   path)
Expand ~ and ~user constructions.  If user or $HOME is unknown,
do nothing.

Definition at line 235 of file posixpath.py.

00235 
00236 def expanduser(path):
00237     """Expand ~ and ~user constructions.  If user or $HOME is unknown,
00238     do nothing."""
00239     if isinstance(path, bytes):
00240         tilde = b'~'
00241     else:
00242         tilde = '~'
00243     if not path.startswith(tilde):
00244         return path
00245     sep = _get_sep(path)
00246     i = path.find(sep, 1)
00247     if i < 0:
00248         i = len(path)
00249     if i == 1:
00250         if 'HOME' not in os.environ:
00251             import pwd
00252             userhome = pwd.getpwuid(os.getuid()).pw_dir
00253         else:
00254             userhome = os.environ['HOME']
00255     else:
00256         import pwd
00257         name = path[1:i]
00258         if isinstance(name, bytes):
00259             name = str(name, 'ASCII')
00260         try:
00261             pwent = pwd.getpwnam(name)
00262         except KeyError:
00263             return path
00264         userhome = pwent.pw_dir
00265     if isinstance(path, bytes):
00266         userhome = os.fsencode(userhome)
00267         root = b'/'
00268     else:
00269         root = '/'
00270     userhome = userhome.rstrip(root) or userhome
00271     return userhome + path[i:]
00272 
00273 
00274 # Expand paths containing shell variable substitutions.
00275 # This expands the forms $variable and ${variable} only.
00276 # Non-existent variables are left unchanged.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.expandvars (   path)
Expand shell variables of form $var and ${var}.  Unknown variables
are left unchanged.

Definition at line 280 of file posixpath.py.

00280 
00281 def expandvars(path):
00282     """Expand shell variables of form $var and ${var}.  Unknown variables
00283     are left unchanged."""
00284     global _varprog, _varprogb
00285     if isinstance(path, bytes):
00286         if b'$' not in path:
00287             return path
00288         if not _varprogb:
00289             import re
00290             _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
00291         search = _varprogb.search
00292         start = b'{'
00293         end = b'}'
00294     else:
00295         if '$' not in path:
00296             return path
00297         if not _varprog:
00298             import re
00299             _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
00300         search = _varprog.search
00301         start = '{'
00302         end = '}'
00303     i = 0
00304     while True:
00305         m = search(path, i)
00306         if not m:
00307             break
00308         i, j = m.span(0)
00309         name = m.group(1)
00310         if name.startswith(start) and name.endswith(end):
00311             name = name[1:-1]
00312         if isinstance(name, bytes):
00313             name = str(name, 'ASCII')
00314         if name in os.environ:
00315             tail = path[j:]
00316             value = os.environ[name]
00317             if isinstance(path, bytes):
00318                 value = value.encode('ASCII')
00319             path = path[:i] + value
00320             i = len(path)
00321             path += tail
00322         else:
00323             i = j
00324     return path
00325 
00326 
00327 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
00328 # It should be understood that this may change the meaning of the path
00329 # if it contains symbolic links!

Here is the call graph for this function:

def posixpath.isabs (   s)
Test whether a path is absolute

Definition at line 61 of file posixpath.py.

00061 
00062 def isabs(s):
00063     """Test whether a path is absolute"""
00064     sep = _get_sep(s)
00065     return s.startswith(sep)
00066 
00067 
00068 # Join pathnames.
00069 # Ignore the previous parts if a part is absolute.
00070 # Insert a '/' unless the first part is empty or already ends in '/'.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.islink (   path)
Test whether a path is a symbolic link

Definition at line 151 of file posixpath.py.

00151 
00152 def islink(path):
00153     """Test whether a path is a symbolic link"""
00154     try:
00155         st = os.lstat(path)
00156     except (os.error, AttributeError):
00157         return False
00158     return stat.S_ISLNK(st.st_mode)
00159 
00160 # Being true for dangling symbolic links is also useful.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.ismount (   path)
Test whether a path is a mount point

Definition at line 201 of file posixpath.py.

00201 
00202 def ismount(path):
00203     """Test whether a path is a mount point"""
00204     if islink(path):
00205         # A symlink can never be a mount point
00206         return False
00207     try:
00208         s1 = os.lstat(path)
00209         if isinstance(path, bytes):
00210             parent = join(path, b'..')
00211         else:
00212             parent = join(path, '..')
00213         s2 = os.lstat(parent)
00214     except os.error:
00215         return False # It doesn't exist -- so not a mount point :-)
00216     dev1 = s1.st_dev
00217     dev2 = s2.st_dev
00218     if dev1 != dev2:
00219         return True     # path/.. on a different device as path
00220     ino1 = s1.st_ino
00221     ino2 = s2.st_ino
00222     if ino1 == ino2:
00223         return True     # path/.. is the same i-node as path
00224     return False
00225 
00226 
00227 # Expand paths beginning with '~' or '~user'.
00228 # '~' means $HOME; '~user' means that user's home directory.
00229 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
00230 # the path is returned unchanged (leaving error reporting to whatever
00231 # function is called with the expanded path as argument).
00232 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
00233 # (A function should also be defined to do full *sh-style environment
00234 # variable expansion.)

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.join (   a,
  p 
)
Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded.

Definition at line 71 of file posixpath.py.

00071 
00072 def join(a, *p):
00073     """Join two or more pathname components, inserting '/' as needed.
00074     If any component is an absolute path, all previous path components
00075     will be discarded."""
00076     sep = _get_sep(a)
00077     path = a
00078     for b in p:
00079         if b.startswith(sep):
00080             path = b
00081         elif not path or path.endswith(sep):
00082             path +=  b
00083         else:
00084             path += sep + b
00085     return path
00086 
00087 
00088 # Split a path in head (everything up to the last '/') and tail (the
00089 # rest).  If the path ends in '/', tail will be empty.  If there is no
00090 # '/' in the path, head  will be empty.
00091 # Trailing '/'es are stripped from head unless it is the root.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.lexists (   path)
Test whether a path exists.  Returns True for broken symbolic links

Definition at line 161 of file posixpath.py.

00161 
00162 def lexists(path):
00163     """Test whether a path exists.  Returns True for broken symbolic links"""
00164     try:
00165         os.lstat(path)
00166     except os.error:
00167         return False
00168     return True
00169 
00170 
00171 # Are two filenames really pointing to the same file?

Here is the caller graph for this function:

def posixpath.normcase (   s)
Normalize case of pathname.  Has no effect under Posix

Definition at line 49 of file posixpath.py.

00049 
00050 def normcase(s):
00051     """Normalize case of pathname.  Has no effect under Posix"""
00052     # TODO: on Mac OS X, this should really return s.lower().
00053     if not isinstance(s, (bytes, str)):
00054         raise TypeError("normcase() argument must be str or bytes, "
00055                         "not '{}'".format(s.__class__.__name__))
00056     return s
00057 
00058 
00059 # Return whether a path is absolute.
00060 # Trivial in Posix, harder on the Mac or MS-DOS.

def posixpath.normpath (   path)
Normalize path, eliminating double slashes, etc.

Definition at line 330 of file posixpath.py.

00330 
00331 def normpath(path):
00332     """Normalize path, eliminating double slashes, etc."""
00333     if isinstance(path, bytes):
00334         sep = b'/'
00335         empty = b''
00336         dot = b'.'
00337         dotdot = b'..'
00338     else:
00339         sep = '/'
00340         empty = ''
00341         dot = '.'
00342         dotdot = '..'
00343     if path == empty:
00344         return dot
00345     initial_slashes = path.startswith(sep)
00346     # POSIX allows one or two initial slashes, but treats three or more
00347     # as single slash.
00348     if (initial_slashes and
00349         path.startswith(sep*2) and not path.startswith(sep*3)):
00350         initial_slashes = 2
00351     comps = path.split(sep)
00352     new_comps = []
00353     for comp in comps:
00354         if comp in (empty, dot):
00355             continue
00356         if (comp != dotdot or (not initial_slashes and not new_comps) or
00357              (new_comps and new_comps[-1] == dotdot)):
00358             new_comps.append(comp)
00359         elif new_comps:
00360             new_comps.pop()
00361     comps = new_comps
00362     path = sep.join(comps)
00363     if initial_slashes:
00364         path = sep*initial_slashes + path
00365     return path or dot
00366 

Here is the caller graph for this function:

def posixpath.realpath (   filename)
Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path.

Definition at line 381 of file posixpath.py.

00381 
00382 def realpath(filename):
00383     """Return the canonical path of the specified filename, eliminating any
00384 symbolic links encountered in the path."""
00385     if isinstance(filename, bytes):
00386         sep = b'/'
00387         empty = b''
00388     else:
00389         sep = '/'
00390         empty = ''
00391     if isabs(filename):
00392         bits = [sep] + filename.split(sep)[1:]
00393     else:
00394         bits = [empty] + filename.split(sep)
00395 
00396     for i in range(2, len(bits)+1):
00397         component = join(*bits[0:i])
00398         # Resolve symbolic links.
00399         if islink(component):
00400             resolved = _resolve_link(component)
00401             if resolved is None:
00402                 # Infinite loop -- return original component + rest of the path
00403                 return abspath(join(*([component] + bits[i:])))
00404             else:
00405                 newpath = join(*([resolved] + bits[i:]))
00406                 return realpath(newpath)
00407 
00408     return abspath(filename)
00409 

Here is the call graph for this function:

def posixpath.relpath (   path,
  start = None 
)
Return a relative version of a path

Definition at line 432 of file posixpath.py.

00432 
00433 def relpath(path, start=None):
00434     """Return a relative version of a path"""
00435 
00436     if not path:
00437         raise ValueError("no path specified")
00438 
00439     if isinstance(path, bytes):
00440         curdir = b'.'
00441         sep = b'/'
00442         pardir = b'..'
00443     else:
00444         curdir = '.'
00445         sep = '/'
00446         pardir = '..'
00447 
00448     if start is None:
00449         start = curdir
00450 
00451     start_list = [x for x in abspath(start).split(sep) if x]
00452     path_list = [x for x in abspath(path).split(sep) if x]
00453 
00454     # Work out how much of the filepath is shared by start and path.
00455     i = len(commonprefix([start_list, path_list]))
00456 
00457     rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
00458     if not rel_list:
00459         return curdir
00460     return join(*rel_list)

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.samefile (   f1,
  f2 
)
Test whether two pathnames reference the same actual file

Definition at line 172 of file posixpath.py.

00172 
00173 def samefile(f1, f2):
00174     """Test whether two pathnames reference the same actual file"""
00175     s1 = os.stat(f1)
00176     s2 = os.stat(f2)
00177     return samestat(s1, s2)
00178 
00179 
00180 # Are two open files really referencing the same file?
00181 # (Not necessarily the same file descriptor!)

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.sameopenfile (   fp1,
  fp2 
)
Test whether two open file objects reference the same file

Definition at line 182 of file posixpath.py.

00182 
00183 def sameopenfile(fp1, fp2):
00184     """Test whether two open file objects reference the same file"""
00185     s1 = os.fstat(fp1)
00186     s2 = os.fstat(fp2)
00187     return samestat(s1, s2)
00188 
00189 
00190 # Are two stat buffers (obtained from stat, fstat or lstat)
00191 # describing the same file?

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.samestat (   s1,
  s2 
)
Test whether two stat buffers reference the same file

Definition at line 192 of file posixpath.py.

00192 
00193 def samestat(s1, s2):
00194     """Test whether two stat buffers reference the same file"""
00195     return s1.st_ino == s2.st_ino and \
00196            s1.st_dev == s2.st_dev
00197 
00198 
00199 # Is a path a mount point?
00200 # (Does this work for all UNIXes?  Is it even guaranteed to work by Posix?)

Here is the caller graph for this function:

def posixpath.split (   p)
Split a pathname.  Returns tuple "(head, tail)" where "tail" is
everything after the final slash.  Either part may be empty.

Definition at line 92 of file posixpath.py.

00092 
00093 def split(p):
00094     """Split a pathname.  Returns tuple "(head, tail)" where "tail" is
00095     everything after the final slash.  Either part may be empty."""
00096     sep = _get_sep(p)
00097     i = p.rfind(sep) + 1
00098     head, tail = p[:i], p[i:]
00099     if head and head != sep*len(head):
00100         head = head.rstrip(sep)
00101     return head, tail
00102 
00103 
00104 # Split a path in root and extension.
00105 # The extension is everything starting at the last dot in the last
00106 # pathname component; the root is everything before that.
00107 # It is always true that root + ext == p.

Here is the call graph for this function:

Here is the caller graph for this function:

def posixpath.splitdrive (   p)
Split a pathname into drive and path. On Posix, drive is always
empty.

Definition at line 121 of file posixpath.py.

00121 
00122 def splitdrive(p):
00123     """Split a pathname into drive and path. On Posix, drive is always
00124     empty."""
00125     return p[:0], p
00126 
00127 
00128 # Return the tail (basename) part of a path, same as split(path)[1].

def posixpath.splitext (   p)

Definition at line 108 of file posixpath.py.

00108 
00109 def splitext(p):
00110     if isinstance(p, bytes):
00111         sep = b'/'
00112         extsep = b'.'
00113     else:
00114         sep = '/'
00115         extsep = '.'
00116     return genericpath._splitext(p, sep, None, extsep)
00117 splitext.__doc__ = genericpath._splitext.__doc__
00118 
00119 # Split a pathname into a drive specification and the rest of the
00120 # path.  Useful on DOS/Windows/NT; on Unix, the drive is always empty.

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["normcase","isabs","join","splitdrive","split","splitext",
00002            "basename","dirname","commonprefix","getsize","getmtime",
00003            "getatime","getctime","islink","exists","lexists","isdir","isfile",
00004            "ismount", "expanduser","expandvars","normpath","abspath",
00005            "samefile","sameopenfile","samestat",
00006            "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
00007            "devnull","realpath","supports_unicode_filenames","relpath"]

Definition at line 19 of file posixpath.py.

Definition at line 277 of file posixpath.py.

Definition at line 278 of file posixpath.py.

Definition at line 35 of file posixpath.py.

Definition at line 29 of file posixpath.py.

string posixpath.defpath = ':/bin:/usr/bin'

Definition at line 34 of file posixpath.py.

string posixpath.devnull = '/dev/null'

Definition at line 36 of file posixpath.py.

Definition at line 31 of file posixpath.py.

Definition at line 30 of file posixpath.py.

Definition at line 33 of file posixpath.py.

Definition at line 32 of file posixpath.py.

tuple posixpath.supports_unicode_filenames = (sys.platform == 'darwin')

Definition at line 430 of file posixpath.py.