Package mrv :: Module path :: Class Path
[hide private]
[frames] | no frames]

Class Path

source code

         object --+        
                  |        
         basestring --+    
                      |    
                    str --+
                          |
         object --+       |
                  |       |
interface.Interface --+   |
                      |   |
     interface.iDagItem --+
                          |
                         Path
Known Subclasses:

Represents a filesystem path.

For documentation on individual methods, consult their counterparts in os.path.

Instance Methods [hide private]
 
splitunc(self) source code
 
isunshared(self) source code
 
lexists(self) source code
 
samefile(self, other) source code
 
ctime(self) source code
 
access(self, mode)
Return true if current user has access to this path.
source code
 
statvfs(self)
Perform a statvfs() system call on this path.
source code
 
pathconf(self, name)
see os.pathconf
source code
 
chown(self, uid, gid)
Change file ownership
source code
 
link(self, newpath)
Create a hard link at 'newpath', pointing to this file.
source code
 
symlink(self, newlink)
Create a symbolic link at 'newlink', pointing here.
source code
 
readlink(self)
Return the path to which this symbolic link points.
source code
 
readlinkabs(self)
Return the path to which this symbolic link points.
source code
 
move(self, dest)
Move self to dest
source code
 
chroot(self)
Change the root directory path
source code
 
startfile(self)
see os.startfile
source code

Inherited from str: __contains__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, __getslice__, __gt__, __le__, __len__, __lt__, __mod__, __mul__, __new__, __rmod__, __rmul__, __sizeof__, __str__, capitalize, center, count, decode, encode, endswith, expandtabs, find, format, index, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill

Inherited from str (private): _formatter_field_name_split, _formatter_parser

Inherited from interface.Interface: supports

Inherited from object: __delattr__, __init__, __reduce__, __reduce_ex__, __setattr__, __subclasshook__

    Special Python methods
 
__repr__(self)
repr(x)
source code
 
__add__(self, more)
x+y
source code
 
__radd__(self, other) source code
 
__div__(self, rel)
fp.__div__(rel) == fp / rel == fp.joinpath(rel)
source code
 
__truediv__(self, rel)
fp.__div__(rel) == fp / rel == fp.joinpath(rel)
source code
 
__eq__(self, other)
Comparison method with expanded variables, just to assure the comparison yields the results we would expect
source code
 
__ne__(self, other)
x!=y
source code
 
__hash__(self)
Expanded hash method
source code
    iDagItem Implementation
 
parent(self)
Returns: the parent directory of this Path or None if this is the root
source code
 
children(self, predicate=<function <lambda> at 0x7f8b493dc938>, pattern=None)
Returns: child paths as retrieved by queryiing the file system.
source code
    Operations on path strings.
 
isabs(s)
Test whether a path is absolute
 
abspath(self) source code
 
normcase(self) source code
 
normpath(self) source code
 
realpath(self) source code
 
expanduser(self) source code
 
expandvars(self) source code
 
dirname(self) source code
 
basename(p)
Returns the final component of a pathname
 
expandvars_deep(self)
Expands all environment variables recursively
source code
 
expandvars_deep_or_raise(self)
Expands all environment variables recursively, and raises ValueError if the path still contains variables afterwards
source code
 
expand(self)
Clean up a filename by calling expandvars() and expanduser()
source code
 
containsvars(self)
Returns: True if this path contains environment variables
source code
 
expand_or_raise(self)
non-recursively !
source code
 
namebase(self)
The same as path.basename(), but with one file extension stripped off.
source code
 
ext(self)
The file extension, for example '.py'.
source code
 
drive(self)
The drive specifier, for example 'C:'.
source code
Return (p.parent(), p.basename())
splitpath(p) source code
Return (p.drive, <the rest of p>)
splitdrive(p)
Split the drive specifier from this path.
source code
Return (p.stripext(), p.ext)
splitext(p)
Split the filename extension from this path and return the two parts.
source code
Remove one file extension from the path
stripext(p)
For example, path('/home/guido/python.tar.gz').stripext() returns path('/home/guido/python.tar').
source code
 
joinpath(self, *args)
Join two or more path components, adding a separator character (os.sep) if needed.
source code
 
splitall(self)
Return a list of the path components in this path.
source code
 
relpath(self)
Return this path as a relative path, originating from the current working directory.
source code
 
relpathto(self, dest)
Return a relative path from self to dest.
source code
 
relpathfrom(self, dest)
Return a relative path from dest to self
source code
 
convert_separators(self)
to normpath is that it does not cut trailing separators
source code
 
tolinuxpath(self)
Returns: A path using only slashes as path separator
source code
 
tonative(self)
Convert the path separator to the type required by the current operating system - on windows / becomes and on linux becomes /
source code
    Listing, searching, walking, and matching
 
listdir(self, pattern=None)
return list of items in this directory.
source code
List of this directory's subdirectories
dirs(D)
The elements of the list are path objects.
source code
List of the files in this directory
files(D)
The elements of the list are path objects.
source code
 
walk(self, pattern=None, errors='strict', predicate=<function <lambda> at 0x7f8b493df9b0>)
create iterator over files and subdirs, recursively.
source code
iterator over subdirs, recursively
walkdirs(D)
see walk for a parameter description
source code
iterator over files in D, recursively
walkfiles(D)
see walk for a parameter description
source code
 
fnmatch(self, pattern)
Return True if self.basename() matches the given pattern.
source code
 
glob(self, pattern)
Return a list of path objects that match the pattern.
source code
    Reading or writing an entire file at once
 
open(self, *args, **kwargs)
Open this file.
source code
 
bytes(self)
Open this file, read all bytes, return them as a string.
source code
 
write_bytes(self, bytes, append=False)
Open this file and write the given bytes to it.
source code
 
text(self, encoding=None, errors='strict')
Open this file, read it in, return the content as a string.
source code
 
write_text(self, text, encoding=None, errors='strict', linesep='\n', append=False)
Write the given text to this file.
source code
 
write_lines(self, lines, encoding=None, errors='strict', linesep='\n', append=False)
Write the given lines of text to this file.
source code
 
lines(self, encoding=None, errors='strict', retain=True)
Open this file, read all lines, return them in a list.
source code
 
digest(self, hashobject)
Calculate the hash for this file using the given hashobject.
source code
    Methods for querying the filesystem
 
exists(self) source code
 
isdir(self) source code
 
isfile(self) source code
 
islink(self) source code
 
ismount(self) source code
 
atime(self) source code
 
mtime(self) source code
 
size(self) source code
 
stat(self)
Perform a stat() system call on this path.
source code
 
lstat(self)
Like path.stat(), but do not follow symbolic links.
source code
 
owner(self)
Return the name of the owner of this file or directory.
source code
 
isWritable(self)
Returns: true if the file can be written to
source code
    Modifying operations on files and directories
 
setutime(self, times)
Set the access and modified times of this file.
source code
 
chmod(self, mode)
Change file mode
source code
 
rename(self, new)
os.rename
source code
 
renames(self, new)
os.renames, super rename
source code
    Create/delete operations on directories
 
mkdir(self, mode=511)
Make this directory, fail if it already exists
source code
 
makedirs(self, mode=511)
Smarter makedir, see os.makedirs
source code
 
rmdir(self)
Remove this empty directory
source code
 
removedirs(self)
see os.removedirs
source code
    Modifying operations on files
 
touch(self, flags=65, mode=438)
Set the access/modified times of this file to the current time.
source code
 
remove(self)
Remove this file
source code
 
unlink(self)
unlink this file
source code
    High-level functions from shutil
 
copyfile(self, dest)
Copy self to dest
source code
 
copymode(self, dest)
Copy our mode to dest
source code
 
copystat(self, dest)
Copy our stats to dest
source code
 
copy(self, dest)
Copy data and source bits to dest
source code
 
copy2(self, dest)
Shutil.copy2 self to dest
source code
 
copytree(self, dest, **kwargs)
Deep copy this file or directory to destination
source code
 
rmtree(self, **kwargs)
Remove self recursively
source code
    Query Methods

Inherited from interface.iDagItem: childrenDeep, isPartOf, isRoot, isRootOf, parentDeep, root

    Iterators

Inherited from interface.iDagItem: iterParents

    Name Generation

Inherited from interface.iDagItem: fullChildName

Class Methods [hide private]
 
set_separator(cls, sep)
Set this type to support the given separator as general path separator
source code
 
getcwd(cls)
Returns: the current working directory as a path object.
source code
    Operations on path strings.
 
_expandvars(cls, path)
Internal version returning a string only representing the non-recursively expanded variable
source code
 
_expandvars_deep(cls, path)
As above, but recursively expands as many variables as possible
source code
    Name Generation

Inherited from interface.iDagItem: addSep

Class Variables [hide private]
  sep = '/'
  osep = '\\'

Inherited from interface.iDagItem: kOrder_BreadthFirst, kOrder_DepthFirst

    Configuration

Inherited from interface.iDagItem (private): _sep

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__repr__(self)
(Representation operator)

source code 

repr(x)

Overrides: object.__repr__
(inherited documentation)

__add__(self, more)
(Addition operator)

source code 

x+y

Overrides: str.__add__
(inherited documentation)

__div__(self, rel)

source code 

fp.__div__(rel) == fp / rel == fp.joinpath(rel)

Join two path components, adding a separator character if needed.

__truediv__(self, rel)

source code 

fp.__div__(rel) == fp / rel == fp.joinpath(rel)

Join two path components, adding a separator character if needed.

__eq__(self, other)
(Equality operator)

source code 
Comparison method with expanded variables, just to assure the comparison yields the results we would expect
Overrides: str.__eq__

__ne__(self, other)

source code 

x!=y

Overrides: str.__ne__
(inherited documentation)

__hash__(self)
(Hashing function)

source code 
Expanded hash method
Overrides: object.__hash__

getcwd(cls)
Class Method

source code 
Returns:
the current working directory as a path object.

parent(self)

source code 
Returns:
the parent directory of this Path or None if this is the root
Overrides: interface.iDagItem.parent

children(self, predicate=<function <lambda> at 0x7f8b493dc938>, pattern=None)

source code 
Parameters:
  • predicate - return p if predicate( p ) returns True
  • pattern - list only elements that match the given simple pattern i.e. .
Returns:
child paths as retrieved by queryiing the file system.
Overrides: interface.iDagItem.children

Note: files cannot have children, and willl return an empty array accordingly

_expandvars(cls, path)
Class Method

source code 
Internal version returning a string only representing the non-recursively expanded variable

Note: It is a slightly changed copy of the version in posixfile as the windows version was implemented differently ( it expands variables to an empty space which is undesireable )

basename(p)

 

Returns the final component of a pathname

Returns:
basename of this path, '/hello/world' -> 'world'
Overrides: interface.iDagItem.basename

expand(self)

source code 

Clean up a filename by calling expandvars() and expanduser()

This is commonly everything needed to clean up a filename read from a configuration file, for example.

If you are not interested in trailing slashes, you should call normpath() on the resulting Path as well.

containsvars(self)

source code 
Returns:
True if this path contains environment variables

expand_or_raise(self)

source code 
non-recursively !
Returns:
Copy of self with all variables expanded ( using expand )
Raises:
  • ValueError - If we could not expand all environment variables as their values where missing in the environment

namebase(self)

source code 

The same as path.basename(), but with one file extension stripped off.

For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz', but path('/home/guido/python.tar.gz').namebase == 'python.tar'

drive(self)

source code 
The drive specifier, for example 'C:'. This is always empty on systems that don't use drive specifiers.

splitdrive(p)

source code 
Split the drive specifier from this path. If there is no drive specifier, p.drive is empty, so the return value is simply (path(''), p). This is always the case on Unix.
Returns: Return (p.drive, <the rest of p>)

splitext(p)

source code 

Split the filename extension from this path and return the two parts. Either part may be empty.

The extension is everything from '.' to the end of the last path segment. This has the property that if (a, b) == p.splitext(), then a + b == p.

Returns: Return (p.stripext(), p.ext)

joinpath(self, *args)

source code 
Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object.

splitall(self)

source code 

Return a list of the path components in this path.

The first item in the list will be a path. Its value will be either os.curdir, os.pardir, empty, or the root directory of this path (for example, '/' or 'C:'). The other items in the list will be strings.

path.path.joinpath(*result) can possibly yield the original path, depending on the input.

relpathto(self, dest)

source code 

Return a relative path from self to dest.

If there is no relative path from self to dest, for example if they reside on different drives in Windows, then this returns dest.abspath().

convert_separators(self)

source code 
to normpath is that it does not cut trailing separators
Returns:
Version of self with all separators set to be 'sep'. The difference

tolinuxpath(self)

source code 
Returns:
A path using only slashes as path separator

tonative(self)

source code 
Convert the path separator to the type required by the current operating system - on windows / becomes and on linux becomes /
Returns:
native version of self

listdir(self, pattern=None)

source code 

return list of items in this directory.

Use D.files() or D.dirs() instead if you want a listing of just files or just subdirectories.

The elements of the list are path objects.

With the optional 'pattern' argument, this only lists items whose names match the given pattern.

dirs(D)

source code 

The elements of the list are path objects. This does not walk recursively into subdirectories (but see path.walkdirs).

With the optional pattern argument, this only lists directories whose names match the given pattern. For example, d.dirs("build-*").

Returns: List of this directory's subdirectories

files(D)

source code 

The elements of the list are path objects. This does not walk into subdirectories (see path.walkfiles).

With the optional pattern argument, this only lists files whose names match the given pattern. For example, d.files("*.pyc").

Returns: List of the files in this directory

walk(self, pattern=None, errors='strict', predicate=<function <lambda> at 0x7f8b493df9b0>)

source code 

create iterator over files and subdirs, recursively.

The iterator yields path objects naming each child item of this directory and its descendants.

It performs a depth-first traversal of the directory tree. Each directory is returned just before all its children.

Parameters:
  • pattern - fnmatch compatible pattern or None
  • errors - controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via log.warn(), and 'ignore'.
  • predicate - returns True for each Path p to be yielded by iterator

fnmatch(self, pattern)

source code 

Return True if self.basename() matches the given pattern.

pattern - A filename pattern with wildcards,
for example "*.py".

glob(self, pattern)

source code 

Return a list of path objects that match the pattern.

pattern - a path relative to this directory, with wildcards.

For example, path('/users').glob('/bin/') returns a list of all the files users have in their bin directories.

open(self, *args, **kwargs)

source code 
Open this file. Return a file object.

write_bytes(self, bytes, append=False)

source code 

Open this file and write the given bytes to it.

Default behavior is to overwrite any existing file. Call p.write_bytes(bytes, append=True) to append instead. :return: self

text(self, encoding=None, errors='strict')

source code 

Open this file, read it in, return the content as a string.

This uses "U" mode in Python 2.3 and later, so "rn" and "r" are automatically translated to 'n'.

Optional arguments:
  • encoding - The Unicode encoding (or character set) of the file. If present, the content of the file is decoded and returned as a unicode object; otherwise it is returned as an 8-bit str.
  • errors - How to handle Unicode errors; see help(str.decode) for the options. Default is 'strict'.

write_text(self, text, encoding=None, errors='strict', linesep='\n', append=False)

source code 

Write the given text to this file.

The default behavior is to overwrite any existing file; to append instead, use the 'append=True' keyword argument.

There are two differences between path.write_text() and path.write_bytes(): newline handling and Unicode handling. See below.

Parameters:
  • text - str/unicode - The text to be written.

  • encoding - str - The Unicode encoding that will be used.

    This is ignored if 'text' isn't a Unicode string.

  • errors - str - How to handle Unicode encoding errors.

    Default is 'strict'. See help(unicode.encode) for the options. This is ignored if 'text' isn't a Unicode string.

  • linesep - keyword argument - str/unicode - The sequence of

    characters to be used to mark end-of-line. The default is os.linesep. You can also specify None; this means to leave all newlines as they are in 'text'.

  • append - keyword argument - bool - Specifies what to do if

    the file already exists (True: append to the end of it; False: overwrite it.) The default is False.

Newline handling:
  • write_text() converts all standard end-of-line sequences

    ("n", "r", and "rn") to your platforms default end-of-line sequence (see os.linesep; on Windows, for example, the end-of-line marker is "rn").

  • If you don't like your platform's default, you can override it

    using the "linesep=" keyword argument. If you specifically want write_text() to preserve the newlines as-is, use "linesep=None".

  • This applies to Unicode text the same as to 8-bit text, except

    there are additional standard Unicode end-of-line sequences, check the code to see them.

  • (This is slightly different from when you open a file for

    writing with fopen(filename, "w") in C or file(filename, "w") in Python.)

Unicode:

If "text" isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The "encoding" and 'errors' arguments are not used and must be omitted.

If 'text' is Unicode, it is first converted to bytes using the specified 'encoding' (or the default encoding if 'encoding' isn't specified). The 'errors' argument applies only to this conversion.

Returns:
self

write_lines(self, lines, encoding=None, errors='strict', linesep='\n', append=False)

source code 

Write the given lines of text to this file.

By default this overwrites any existing file at this path.

This puts a platform-specific newline sequence on every line. See 'linesep' below.

lines - A list of strings.

encoding - A Unicode encoding to use. This applies only if
'lines' contains any Unicode strings.
errors - How to handle errors in Unicode encoding. This
also applies only to Unicode strings.
linesep - The desired line-ending. This line-ending is
applied to every line. If a line already has any standard line ending, that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent ('rn' on Windows, 'n' on Unix, etc.) Specify None to write the lines as-is, like file.writelines().

Use the keyword argument append=True to append lines to the file. The default is to overwrite the file. Warning: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the encoding= parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later.

Returns:
self

lines(self, encoding=None, errors='strict', retain=True)

source code 

Open this file, read all lines, return them in a list.

Optional arguments:
  • encoding: The Unicode encoding (or character set) of

    the file. The default is None, meaning the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects.

  • errors: How to handle Unicode errors; see help(str.decode)

    for the options. Default is 'strict'

  • retain: If true, retain newline characters; but all newline

    character combinations ("r", "n", "rn") are translated to "n". If false, newline characters are stripped off. Default is True.

This uses "U" mode in Python 2.3 and later.

digest(self, hashobject)

source code 
Calculate the hash for this file using the given hashobject. It must support the 'update' and 'digest' methods.

Note: This reads through the entire file.

access(self, mode)

source code 

Return true if current user has access to this path.

mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK

owner(self)

source code 

Return the name of the owner of this file or directory.

This follows symbolic links.

On Windows, this returns a name of the form ur'DOMAINUser Name'. On Windows, a group can own a file or directory.

isWritable(self)

source code 
Returns:
true if the file can be written to

setutime(self, times)

source code 
Set the access and modified times of this file.
Returns:
self

chmod(self, mode)

source code 
Change file mode
Returns:
self

chown(self, uid, gid)

source code 
Change file ownership
Returns:
self

rename(self, new)

source code 
os.rename
Returns:
Path to new file

renames(self, new)

source code 
os.renames, super rename
Returns:
Path to new file

mkdir(self, mode=511)

source code 
Make this directory, fail if it already exists
Returns:
self

makedirs(self, mode=511)

source code 
Smarter makedir, see os.makedirs
Returns:
self

rmdir(self)

source code 
Remove this empty directory
Returns:
self

removedirs(self)

source code 
see os.removedirs
Returns:
self

touch(self, flags=65, mode=438)

source code 
Set the access/modified times of this file to the current time. Create the file if it does not exist.
Returns:
self

remove(self)

source code 
Remove this file
Returns:
self

unlink(self)

source code 
unlink this file
Returns:
self

link(self, newpath)

source code 
Create a hard link at 'newpath', pointing to this file.
Returns:
Path to newpath

symlink(self, newlink)

source code 
Create a symbolic link at 'newlink', pointing here.
Returns:
Path to newlink

readlink(self)

source code 

Return the path to which this symbolic link points.

The result may be an absolute or a relative path.

readlinkabs(self)

source code 

Return the path to which this symbolic link points.

The result is always an absolute path.

copyfile(self, dest)

source code 
Copy self to dest
Returns:
Path to dest

copymode(self, dest)

source code 
Copy our mode to dest
Returns:
Path to dest

copystat(self, dest)

source code 
Copy our stats to dest
Returns:
Path to dest

copy(self, dest)

source code 
Copy data and source bits to dest
Returns:
Path to dest

copy2(self, dest)

source code 
Shutil.copy2 self to dest
Returns:
Path to dest

copytree(self, dest, **kwargs)

source code 
Deep copy this file or directory to destination
Parameters:
  • kwargs - passed to shutil.copytree
Returns:
Path to dest

move(self, dest)

source code 
Move self to dest
Returns:
Path to dest

rmtree(self, **kwargs)

source code 
Remove self recursively
Parameters:
  • kwargs - passed to shutil.rmtree
Returns:
self

chroot(self)

source code 
Change the root directory path
Returns:
self

startfile(self)

source code 
see os.startfile
Returns:
self