path - read the docspath.py, release 11.4.2.dev11+g1bab564.d20181002 since copytree() is called...

38
path.py Release 11.4.2.dev11+g1bab564.d20181002 Oct 02, 2018

Upload: others

Post on 12-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.pyRelease 11.4.2.dev11+g1bab564.d20181002

Oct 02, 2018

Page 2: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It
Page 3: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

Contents

1 API 3

2 History 19

3 Indices and tables 29

Python Module Index 31

i

Page 4: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

ii

Page 5: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

Contents:

Contents 1

Page 6: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2 Contents

Page 7: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

CHAPTER 1

API

Important: The documented methods’ signatures are not always correct. See path.Path.

path.py - An object representing a path to a file or directory.

https://github.com/jaraco/path.py

Example:

from path import Pathd = Path('/home/guido/bin')

# Globbingfor f in d.files('*.py'):

f.chmod(0o755)

# Changing the working directory:with Path("somewhere"):

# cwd in now `somewhere`...

# Concatenate paths with /foo_txt = Path("bar") / "foo.txt"

class path.Path(other=”)Represents a filesystem path.

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

Some methods are additionally included from shutil. The functions are linked directly into the class names-pace such that they will be bound to the Path instance. For example, Path(src).copy(target) is equiv-alent to shutil.copy(src, target). Therefore, when referencing the docs for these methods, assumesrc references self, the Path instance.

abspath()

3

Page 8: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

See also:

os.path.abspath()

access(mode)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

See also:

os.access()

atimeLast access time of the file.

See also:

getatime(), os.path.getatime()

basename()

See also:

name, os.path.basename()

bytes()Open this file, read all bytes, return them as a string.

cd()

See also:

os.chdir()

chdir()

See also:

os.chdir()

chmod(mode)Set the mode. May be the new mode (os.chmod behavior) or a symbolic mode.

See also:

os.chmod()

chown(uid=-1, gid=-1)Change the owner and group by names rather than the uid or gid numbers.

See also:

os.chown()

chroot()

See also:

os.chroot()

chunks(size, *args, **kwargs)

Returns a generator yielding chunks of the file, so it can be read piece by piece with a simple for loop.

4 Chapter 1. API

Page 9: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

Any argument you pass after size will be passed to open().

Example

>>> hash = hashlib.md5()>>> for chunk in Path("path.py").chunks(8192, mode='rb'):... hash.update(chunk)

This will read the file by chunks of 8192 bytes.

copy(dst, *, follow_symlinks=True)Copy data and mode bits (“cp src dst”). Return the file’s destination.

The destination may be a directory.

If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.

If source and destination are the same file, a SameFileError will be raised.

copy2(dst, *, follow_symlinks=True)Copy data and all stat info (“cp -p src dst”). Return the file’s destination.”

The destination may be a directory.

If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.

copyfile(dst, *, follow_symlinks=True)Copy data from src to dst.

If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copyingthe file it points to.

copymode(dst, *, follow_symlinks=True)Copy mode bits from src to dst.

If follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst are symlinks. Iflchmod isn’t available (e.g. Linux) this method does nothing.

copystat(dst, *, follow_symlinks=True)Copy all stat info (mode bits, atime, mtime, flags) from src to dst.

If the optional flag follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst aresymlinks.

copytree(dst, symlinks=False, ignore=None, copy_function=<function copy2>, ig-nore_dangling_symlinks=False)

Recursively copy a directory tree.

The destination directory must not already exist. If exception(s) occur, an Error is raised with a list ofreasons.

If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in thedestination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the filepointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Errorexception at the end of the copy process.

You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Noticethat this has no effect on platforms that don’t support os.symlink.

The optional ignore argument is a callable. If given, it is called with the src parameter, which is thedirectory being visited by copytree(), and names which is the list of src contents, as returned by os.listdir():

callable(src, names) -> ignored_names

5

Page 10: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

Since copytree() is called recursively, the callable will be called once for each directory that is copied. Itreturns a list of names relative to the src directory that should not be copied.

The optional copy_function argument is a callable that will be used to copy each file. It will be called withthe source path and the destination path as arguments. By default, copy2() is used, but any function thatsupports the same signature (like copy()) can be used.

ctimeCreation time of the file.

See also:

getctime(), os.path.getctime()

dirname()

See also:

parent, os.path.dirname()

dirs()→ List of this directory’s subdirectories.The elements of the list are Path objects. This does not walk recursively into subdirectories (but seewalkdirs()).

Accepts parameters to listdir().

driveThe drive specifier, for example 'C:'.

This is always empty on systems that don’t use drive specifiers.

exists()

See also:

os.path.exists()

expand()Clean up a filename by calling expandvars(), expanduser(), and normpath() on it.

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

expanduser()

See also:

os.path.expanduser()

expandvars()

See also:

os.path.expandvars()

extThe file extension, for example '.py'.

files()→ List of the files in this directory.The elements of the list are Path objects. This does not walk into subdirectories (see walkfiles()).

Accepts parameters to listdir().

6 Chapter 1. API

Page 11: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

fnmatch(pattern, normcase=None)Return True if self.name matches the given pattern.

pattern - A filename pattern with wildcards, for example '*.py'. If the pattern contains a normcaseattribute, it is applied to the name and path prior to comparison.

normcase - (optional) A function used to normalize the pattern and filename before matching. De-faults to self.module(), which defaults to os.path.normcase().

See also:

fnmatch.fnmatch()

get_owner()Return the name of the owner of this file or directory. Follow symbolic links.

See also:

owner

getatime()

See also:

atime, os.path.getatime()

getctime()

See also:

ctime, os.path.getctime()

classmethod getcwd()Return the current working directory as a path object.

See also:

os.getcwdu()

getmtime()

See also:

mtime, os.path.getmtime()

getsize()

See also:

size, os.path.getsize()

glob(pattern)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 theirbin directories.

See also:

glob.glob()

7

Page 12: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

Note: Glob is not recursive, even when using **. To do recursive globbing see walk(), walkdirs()or walkfiles().

iglob(pattern)Return an iterator of Path objects that match the pattern.

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

For example, Path('/users').iglob('*/bin/*') returns an iterator of all the files users havein their bin directories.

See also:

glob.iglob()

Note: Glob is not recursive, even when using **. To do recursive globbing see walk(), walkdirs()or walkfiles().

in_place(mode=’r’, buffering=-1, encoding=None, errors=None, newline=None,backup_extension=None)

A context in which a file may be re-written in-place with new content.

Yields a tuple of (readable, writable) file objects, where writable replaces readable.

If an exception occurs, the old file is restored, removing the written data.

Mode must not use 'w', 'a', or '+'; only read-only-modes are allowed. A ValueError is raised oninvalid modes.

For example, to add line numbers to a file:

p = Path(filename)assert p.isfile()with p.in_place() as (reader, writer):

for number, line in enumerate(reader, 1):writer.write('{0:3}: '.format(number)))writer.write(line)

Thereafter, the file at filename will have line numbers in it.

isabs()

See also:

os.path.isabs()

isdir()

See also:

os.path.isdir()

isfile()

See also:

os.path.isfile()

8 Chapter 1. API

Page 13: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

islink()

See also:

os.path.islink()

ismount()

See also:

os.path.ismount()

joinpath = functools.partial(<function Path.joinpath>, <class 'path.Path'>)

lines(encoding=None, errors=’strict’, retain=True)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 thecontent 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', '\r\n') are translated to '\n'. If False, newline characters are stripped off. Defaultis True.

See also:

text()

link(newpath)Create a hard link at newpath, pointing to this file.

See also:

os.link()

listdir()→ List of items in this directory.Use files() or dirs() instead if you want a listing of just files or just subdirectories.

The elements of the list are Path objects.

With the optional match argument, a callable, only return items whose names match the given pattern.

See also:

files(), dirs()

lstat()Like stat(), but do not follow symbolic links.

See also:

stat(), os.lstat()

makedirs(mode=511)

See also:

os.makedirs()

9

Page 14: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

makedirs_p(mode=511)Like makedirs(), but does not raise an exception if the directory already exists.

merge_tree(dst, symlinks=False, update=False, copy_function=<function copy2>, ignore=<functionPath.<lambda>>)

Copy entire contents of self to dst, overwriting existing contents in dst with those in self.

Pass symlinks=True to copy symbolic links as links.

Accepts a copy_function, similar to copytree.

To avoid overwriting newer files, supply a copy function wrapped in only_newer. For example:

src.merge_tree(dst, copy_function=only_newer(shutil.copy2))

mkdir(mode=511)

See also:

os.mkdir()

mkdir_p(mode=511)Like mkdir(), but does not raise an exception if the directory already exists.

module = <module 'posixpath' from '/home/docs/checkouts/readthedocs.org/user_builds/pathpy/envs/latest/lib/python3.5/posixpath.py'>The path module to use for path operations.

See also:

os.path

move(dst, copy_function=<function copy2>)Recursively move a file or directory to another location. This is similar to the Unix “mv” command. Returnthe file or directory’s destination.

If the destination is a directory or a symlink to a directory, the source is moved inside the directory. Thedestination path must not already exist.

If the destination already exists but is not a directory, it may be overwritten depending on os.rename()semantics.

If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to thedestination and then removed. Symlinks are recreated under the new name if os.rename() fails because ofcross filesystem renames.

The optional copy_function argument is a callable that will be used to copy the source or it will be delegatedto copytree. By default, copy2() is used, but any function that supports the same signature (like copy())can be used.

A lot more could be done here. . . A look at a mv.c shows a lot of the issues this implementation glossesover.

mtimeLast-modified time of the file.

See also:

getmtime(), os.path.getmtime()

nameThe name of this file or directory without the full path.

For example, Path('/usr/local/lib/libpython.so').name == 'libpython.so'

10 Chapter 1. API

Page 15: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

See also:

basename(), os.path.basename()

namebase

normcase()

See also:

os.path.normcase()

normpath()

See also:

os.path.normpath()

open(*args, **kwargs)Open this file and return a corresponding file object.

Keyword arguments work as in io.open(). If the file cannot be opened, an OSError is raised.

ownerName of the owner of this file or directory.

See also:

get_owner()

parentThis path’s parent directory, as a new Path object.

For example, Path('/usr/local/lib/libpython.so').parent == Path('/usr/local/lib')

See also:

dirname(), os.path.dirname()

pathconf(name)

See also:

os.pathconf()

read_hash(hash_name)Calculate given hash for this file.

List of supported hashes can be obtained from hashlib package. This reads the entire file.

See also:

hashlib.hash.digest()

read_hexhash(hash_name)Calculate given hash for this file, returning hexdigest.

List of supported hashes can be obtained from hashlib package. This reads the entire file.

See also:

hashlib.hash.hexdigest()

11

Page 16: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

read_md5()Calculate the md5 hash for this file.

This reads through the entire file.

See also:

read_hash()

readlink()Return the path to which this symbolic link points.

The result may be an absolute or a relative path.

See also:

readlinkabs(), os.readlink()

readlinkabs()Return the path to which this symbolic link points.

The result is always an absolute path.

See also:

readlink(), os.readlink()

realpath()

See also:

os.path.realpath()

relpath(start=’.’)Return this path as a relative path, based from start, which defaults to the current working directory.

relpathto(dest)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, thenthis returns dest.abspath().

remove()

See also:

os.remove()

remove_p()Like remove(), but does not raise an exception if the file does not exist.

removedirs()

See also:

os.removedirs()

removedirs_p()Like removedirs(), but does not raise an exception if the directory is not empty or does not exist.

rename(new)

See also:

12 Chapter 1. API

Page 17: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

os.rename()

renames(new)

See also:

os.renames()

rmdir()

See also:

os.rmdir()

rmdir_p()Like rmdir(), but does not raise an exception if the directory is not empty or does not exist.

rmtree(ignore_errors=False, onerror=None)Recursively delete a directory tree.

If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the errorwith arguments (func, path, exc_info) where func is platform and implementation dependent; path is theargument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). Ifignore_errors is false and onerror is None, an exception is raised.

rmtree_p()Like rmtree(), but does not raise an exception if the directory does not exist.

samefile(other)

See also:

os.path.samefile()

sizeSize of the file, in bytes.

See also:

getsize(), os.path.getsize()

special = functools.partial(<class 'path.SpecialResolver'>, <class 'path.Path'>)

splitall()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 theroot directory of this path (for example, '/' or 'C:\\'). The other items in the list will be strings.

path.Path.joinpath(*result) will yield the original path.

splitdrive()→ Return ‘‘(p.drive, <the rest of p>)‘‘.Split the drive specifier from this path. If there is no drive specifier, p.drive is empty, so the return valueis simply (Path(''), p). This is always the case on Unix.

See also:

os.path.splitdrive()

splitext()→ Return ‘‘(p.stripext(), p.ext)‘‘.Split the filename extension from this path and return the two parts. Either part may be empty.

13

Page 18: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

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.

See also:

os.path.splitext()

splitpath()→ Return ‘‘(p.parent, p.name)‘‘.

See also:

parent, name, os.path.split()

splitunc()

See also:

os.path.splitunc()

stat()Perform a stat() system call on this path.

See also:

lstat(), os.stat()

statvfs()Perform a statvfs() system call on this path.

See also:

os.statvfs()

stemThe same as name(), but with one file extension stripped off.

>>> Path('/home/guido/python.tar.gz').stem'python.tar'

stripext()→ Remove one file extension from the path.For example, Path('/home/guido/python.tar.gz').stripext() returns Path('/home/guido/python.tar').

symlink(newlink=None)Create a symbolic link at newlink, pointing here.

If newlink is not supplied, the symbolic link will assume the name self.basename(), creating the link in thecwd.

See also:

os.symlink()

text(encoding=None, errors=’strict’)Open this file, read it in, return the content as a string.

All newline sequences are converted to '\n'. Keyword arguments will be passed to open().

See also:

lines()

touch()Set the access/modified times of this file to the current time. Create the file if it does not exist.

14 Chapter 1. API

Page 19: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

uncshareThe UNC mount point for this path. This is empty for paths on local drives.

unlink()

See also:

os.unlink()

unlink_p()Like unlink(), but does not raise an exception if the file does not exist.

classmethod using_module(module)

utime(times)Set the access and modified times of this file.

See also:

os.utime()

walk()→ iterator over files and subdirs, recursively.The iterator yields Path objects naming each child item of this directory and its descendants. This requiresthat D.isdir().

This performs a depth-first traversal of the directory tree. Each directory is returned just before all itschildren.

The errors= keyword argument controls behavior when an error occurs. The default is 'strict',which causes an exception. Other allowed values are 'warn' (which reports the error via warnings.warn()), and 'ignore'. errors may also be an arbitrary callable taking a msg parameter.

walkdirs()→ iterator over subdirs, recursively.

walkfiles()→ iterator over files in D, recursively.

with_suffix(suffix)Return a new path with the file suffix changed (or added, if none)

>>> Path('/home/guido/python.tar.gz').with_suffix(".foo")Path('/home/guido/python.tar.foo')

>>> Path('python').with_suffix('.zip')Path('python.zip')

>>> Path('filename.ext').with_suffix('zip')Traceback (most recent call last):...ValueError: Invalid suffix 'zip'

write_bytes(bytes, append=False)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.

write_lines(lines, encoding=None, errors=’strict’, linesep=’\n’, append=False)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.

15

Page 20: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

lines - A list of strings.

encoding - A Unicode encoding to use. This applies only if lines contains any Unicodestrings.

errors - How to handle errors in Unicode encoding. This also applies only to Unicodestrings.

linesep - The desired line-ending. This line-ending is applied to every line. If a line al-ready has any standard line ending ('\r', '\n', '\r\n', u'\x85', u'\r\x85',u'\u2028'), that will be stripped off and this will be used instead. The default is os.linesep,which is platform-dependent ('\r\n' on Windows, '\n' on Unix, etc.). Specify None towrite 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 isdifferent from the encoding you specify with the encoding= parameter, the result is mixed-encodingdata, which can really confuse someone trying to read the file later.

write_text(text, encoding=None, errors=’strict’, linesep=’\n’, append=False)Write the given text to this file.

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

There are two differences between write_text() and write_bytes(): newline handling and Uni-code 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 Uni-code string.

errors - str - How to handle Unicode encoding errors. Default is 'strict'. Seehelp(unicode.encode) for the options. This is ignored if text isn’t a Unicodestring.

linesep - keyword argument - str/unicode - The sequence of characters to be used to markend-of-line. The default is os.linesep. You can also specify None to leave all new-lines as they are in text.

append - keyword argument - bool - Specifies what to do if the file already exists (True: ap-pend 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 '\r\n') to your plat-form’s default end-of-line sequence (see os.linesep; on Windows, for example, the end-of-line markeris '\r\n').

If you don’t like your platform’s default, you can override it using the linesep= keyword argument. If youspecifically 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 three additional standard Unicodeend-of-line sequences: u'\x85', u'\r\x85', and u'\u2028'.

(This is slightly different from when you open a file for writing with fopen(filename, "w") in C oropen(filename, 'w') in Python.)

16 Chapter 1. API

Page 21: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

— Unicode

If text isn’t Unicode, then apart from newline handling, the bytes are written verbatim to the file. Theencoding 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 encodingif encoding isn’t specified). The errors argument applies only to this conversion.

class path.TempDir(*args, **kwargs)A temporary directory via tempfile.mkdtemp(), and constructed with the same parameters that you canuse as a context manager.

Example:

with TempDir() as d:# do stuff with the Path object "d"

# here the directory is deleted automatically

See also:

tempfile.mkdtemp()

class path.CaseInsensitivePattern(value)

17

Page 22: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

18 Chapter 1. API

Page 23: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

CHAPTER 2

History

2.1 11.5.0

• #156: Re-wrote the handling of pattern matches for listdir, walk, and related methods, allowingthe pattern to be a more complex object. This approach drastically simplifies the code and obviates theCaseInsensitivePattern and FastPath classes. Now the main Path class should be as performantas FastPath and case-insensitive matches can be readily constructed using the new path.matchers.CaseInsensitive class.

2.2 11.4.1

29 Sep 2018

• #153: Skip intermittently failing performance test on Python 2.

2.3 11.4.0

28 Sep 2018

• #130: Path.py now supports non-decodable filenames on Linux and Python 2, leveraging the backports.os pack-age (as an optional dependency). Currently, only listdir is patched, but other os primitives may be patchedsimilarly in the patch_for_linux_python2 function.

• #141: For merge_tree, instead of relying on the deprecated distutils module, implement merge_tree explic-itly. The update parameter is deprecated, instead superseded by a copy_function parameter and anonly_newer wrapper for any copy function.

19

Page 24: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.4 11.3.0

18 Sep 2018

• #151: No longer use two techniques for splitting lines. Instead, unconditionally rely on io.open for universalnewlines support and always use splitlines.

2.5 11.2.0

15 Sep 2018

• #146: Rely on importlib_metadata instead of setuptools/pkg_resources to load the version of the module. Addedtests ensuring a <100ms import time for the path module. This change adds an explicit dependency on theimportlib_metadata package, but the project still supports copying of the path.py module without any depen-dencies.

2.6 11.1.0

04 Sep 2018

• #143, #144: Add iglob method.

• #142, #145: Rename tempdir to TempDir and declare it as part of __all__. Retain tempdir for com-patibility for now.

• #145: TempDir.__enter__ no longer returns the TempDir instance, but instead returns a Path instance,suitable for entering to change the current working directory.

2.7 11.0.1

26 Mar 2018

• #136: Fixed test failures on BSD.

• Refreshed package metadata.

2.8 11.0

11 Feb 2018

• Drop support for Python 3.3.

2.9 10.6

11 Feb 2018

• Renamed namebase to stem to match API of pathlib. Kept namebase as a deprecated alias for compatibility.

• Added new with_suffix method, useful for renaming the extension on a Path:

20 Chapter 2. History

Page 25: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

orig = Path('mydir/mypath.bat')renamed = orig.rename(orig.with_suffix('.cmd'))

2.10 10.5

29 Oct 2017

• Packaging refresh and readme updates.

2.11 10.4

27 Aug 2017

• #130: Removed surrogate_escape handler as it’s no longer used.

2.12 10.3.1

17 Apr 2017

• #124: Fixed rmdir_p raising FileNotFoundError when directory does not exist on Windows.

2.13 10.3

16 Apr 2017

• #115: Added a new performance-optimized implementation for listdir operations, optimizing listdir, walk,walkfiles, walkdirs, and fnmatch, presented as the FastPath class.

Please direct feedback on this implementation to the ticket, especially if the performance benefits justify itreplacing the default Path class.

2.14 10.2

16 Apr 2017

• Symlink no longer requires the newlink parameter and will default to the basename of the target in the currentworking directory.

2.15 10.1

23 Jan 2017

• #123: Implement Path.__fspath__ per PEP 519.

2.10. 10.5 21

Page 26: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.16 10.0

02 Jan 2017

• Once again as in 8.0 remove deprecated path.path.

2.17 9.1

02 Jan 2017

• #121: Removed workaround for #61 added in 5.2. path.py now only supports file system paths that can beeffectively decoded to text. It is the responsibility of the system implementer to ensure that filenames on thesystem are decodeable by sys.getfilesystemencoding().

2.18 9.0

19 Nov 2016

• Drop support for Python 2.6 and 3.2 as integration dependencies (pip) no longer support these versions.

2.19 8.3

19 Nov 2016

• Merge with latest skeleton, adding badges and test runs by default under tox instead of pytest-runner.

• Documentation is no longer hosted with PyPI.

2.20 8.2.1

16 Apr 2016

• #112: Update Travis CI usage to only deploy on Python 3.5.

2.21 8.2

08 Apr 2016

• Refreshed project metadata based on jaraco’s project skeleton.

• Releases are now automatically published via Travis-CI.

• #111: More aggressively trap errors when importing pkg_resources.

22 Chapter 2. History

Page 27: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.22 8.1.2

04 Oct 2015

• #105: By using unicode literals, avoid errors rendering the backslash in __get_owner_windows.

2.23 8.1.1

10 Sep 2015

• #102: Reluctantly restored reference to path.path in __all__.

2.24 8.1

27 Aug 2015

• #102: Restored path.path with a DeprecationWarning.

2.25 8.0

27 Aug 2015

Removed path.path. Clients must now refer to the canonical name, path.Path as introduced in 6.2.

2.26 7.7

23 Aug 2015

• #88: Added support for resolving certain directories on a system to platform-friendly locations using the appdirslibrary. The Path.special method returns an SpecialResolver instance that will resolve a path in ascope (i.e. ‘site’ or ‘user’) and class (i.e. ‘config’, ‘cache’, ‘data’). For example, to create a config directory for“My App”:

config_dir = Path.special("My App").user.config.makedirs_p()

config_dir will exist in a user context and will be in a suitable platform-friendly location.

As path.py does not currently have any dependencies, and to retain that expectation for a compatible upgradepath, appdirs must be installed to avoid an ImportError when invoking special.

• #88: In order to support “multipath” results, where multiple paths are returned in a single, os.pathsep-separated string, a new class MultiPath now represents those special results. This functionality is experimentaland may change. Feedback is invited.

2.27 7.6.2

23 Aug 2015

• Re-release of 7.6.1 without unintended feature.

2.22. 8.1.2 23

Page 28: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.28 7.6.1

19 Aug 2015

• #101: Supress error when path.py is not present as a distribution.

2.29 7.6

09 Aug 2015

• Pull Request #100: Add merge_tree method for merging two existing directory trees.

• Uses setuptools_scm for version management.

2.30 7.5

02 Aug 2015

• #97: __rdiv__ and __rtruediv__ are now defined.

2.31 7.4

12 Jul 2015

• #93: chown now appears in docs and raises NotImplementedError if os.chown isn’t present.

• #92: Added compatibility support for .samefile on platforms without os.samefile.

2.32 7.3

14 Apr 2015

• #91: Releases now include a universal wheel.

2.33 7.2

29 Jan 2015

• In chmod, added support for multiple symbolic masks (separated by commas).

• In chmod, fixed issue in setting of symbolic mask with ‘=’ where unreferenced permissions were cleared.

2.34 7.1

22 Jan 2015

• #23: Added support for symbolic masks to .chmod.

24 Chapter 2. History

Page 29: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.35 7.0

05 Oct 2014

• The open method now uses io.open and supports all of the parameters to that function. open will alwaysraise an OSError on failure, even on Python 2.

• Updated write_text to support additional newline patterns.

• The text method now always returns text (never bytes), and thus requires an encoding parameter be suppliedif the default encoding is not sufficient to decode the content of the file.

2.36 6.2

27 Sep 2014

• path class renamed to Path. The path name remains as an alias for compatibility.

2.37 6.1

27 Sep 2014

• chown now accepts names in addition to numeric IDs.

2.38 6.0

22 Sep 2014

• Drop support for Python 2.5. Python 2.6 or later required.

• Installation now requires setuptools.

2.39 5.3

17 Sep 2014

• Allow arbitrary callables to be passed to path.walk errors parameter. Enables workaround for issues such as#73 and #56.

2.40 5.2

12 Jun 2014

• #61: path.listdir now decodes filenames from os.listdir when loading characters from a file. On Python 3, thebehavior is unchanged. On Python 2, the behavior will now mimick that of Python 3, attempting to decode allfilenames and paths using the encoding indicated by sys.getfilesystemencoding(), and escaping anyundecodable characters using the ‘surrogateescape’ handler.

2.35. 7.0 25

Page 30: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.41 5.1

30 Jan 2014

• #53: Added path.in_place for editing files in place.

2.42 5.0

08 Nov 2013

• path.fnmatch now takes an optional parameter normcase and this parameter defaults toself.module.normcase (using case normalization most pertinent to the path object itself). Note that this changemeans that any paths using a custom ntpath module on non-Windows systems will have different fnmatch be-havior. Before:

# on Unix>>> p = path('Foo')>>> p.module = ntpath>>> p.fnmatch('foo')False

After:

# on any OS>>> p = path('Foo')>>> p.module = ntpath>>> p.fnmatch('foo')True

To maintain the original behavior, either don’t define the ‘module’ for the path or supply explicit normcasefunction:

>>> p.fnmatch('foo', normcase=os.path.normcase)# result always varies based on OS, same as fnmatch.fnmatch

For most use-cases, the default behavior should remain the same.

• Issue #50: Methods that accept patterns (listdir, files, dirs, walk, walkdirs, walkfiles, andfnmatch) will now use a normcase attribute if it is present on the pattern parameter. The path mod-ule now provides a CaseInsensitivePattern wrapper for strings suitable for creating case-insensitivepatterns for those methods.

2.43 4.4

27 Oct 2013

• Issue #44: _hash method would open files in text mode, producing invalid results on Windows. Now files areopened in binary mode, producing consistent results.

• Issue #47: Documentation is dramatically improved with Intersphinx links to the Python os.path functions anddocumentation for all methods and properties.

26 Chapter 2. History

Page 31: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.44 4.3

02 Jul 2013

• Issue #32: Add chdir and cd methods.

2.45 4.2

02 Jul 2013

• open() now passes all positional and keyword arguments through to the underlying builtins.open call.

2.46 4.1

28 May 2013

• Native Python 2 and Python 3 support without using 2to3 during the build process.

2.47 4.0

26 May 2013

• Added a chunks() method to a allow quick iteration over pieces of a file at a given path.

• Issue #28: Fix missing argument to samefile.

• Initializer no longer enforces isinstance basestring for the source object. Now any object that supplies__unicode__ can be used by a path (except None). Clients that depend on a ValueError being raisedfor int and other non-string objects should trap these types internally.

• Issue #30: chown no longer requires both uid and gid to be provided and will not mutate the ownership ifnothing is provided.

2.48 3.2

07 May 2013

• Issue #22: __enter__ now returns self.

2.49 3.1

15 Apr 2013

• Issue #20: relpath now supports a “start” parameter to match the signature of os.path.relpath.

2.44. 4.3 27

Page 32: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

2.50 3.0

15 Jan 2013

• Minimum Python version is now 2.5.

2.51 2.6

15 Jan 2013

• Issue #5: Implemented path.tempdir, which returns a path object which is a temporary directory and contextmanager for cleaning up the directory.

• Issue #12: One can now construct path objects from a list of strings by simply using path.joinpath. For example:

path.joinpath('a', 'b', 'c') # orpath.joinpath(*path_elements)

2.52 2.5

14 Jan 2013

• Issue #7: Add the ability to do chaining of operations that formerly only returned None.

• Issue #4: Raise a TypeError when constructed from None.

28 Chapter 2. History

Page 33: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

CHAPTER 3

Indices and tables

• genindex

• modindex

• search

29

Page 34: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

30 Chapter 3. Indices and tables

Page 35: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

Python Module Index

ppath, 3

31

Page 36: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

32 Python Module Index

Page 37: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

Index

Aabspath() (path.Path method), 3access() (path.Path method), 4atime (path.Path attribute), 4

Bbasename() (path.Path method), 4bytes() (path.Path method), 4

CCaseInsensitivePattern (class in path), 17cd() (path.Path method), 4chdir() (path.Path method), 4chmod() (path.Path method), 4chown() (path.Path method), 4chroot() (path.Path method), 4chunks() (path.Path method), 4copy() (path.Path method), 5copy2() (path.Path method), 5copyfile() (path.Path method), 5copymode() (path.Path method), 5copystat() (path.Path method), 5copytree() (path.Path method), 5ctime (path.Path attribute), 6

Ddirname() (path.Path method), 6dirs() (path.Path method), 6drive (path.Path attribute), 6

Eexists() (path.Path method), 6expand() (path.Path method), 6expanduser() (path.Path method), 6expandvars() (path.Path method), 6ext (path.Path attribute), 6

Ffiles() (path.Path method), 6

fnmatch() (path.Path method), 6

Gget_owner() (path.Path method), 7getatime() (path.Path method), 7getctime() (path.Path method), 7getcwd() (path.Path class method), 7getmtime() (path.Path method), 7getsize() (path.Path method), 7glob() (path.Path method), 7

Iiglob() (path.Path method), 8in_place() (path.Path method), 8isabs() (path.Path method), 8isdir() (path.Path method), 8isfile() (path.Path method), 8islink() (path.Path method), 8ismount() (path.Path method), 9

Jjoinpath (path.Path attribute), 9

Llines() (path.Path method), 9link() (path.Path method), 9listdir() (path.Path method), 9lstat() (path.Path method), 9

Mmakedirs() (path.Path method), 9makedirs_p() (path.Path method), 9merge_tree() (path.Path method), 10mkdir() (path.Path method), 10mkdir_p() (path.Path method), 10module (path.Path attribute), 10move() (path.Path method), 10mtime (path.Path attribute), 10

33

Page 38: path - Read the Docspath.py, Release 11.4.2.dev11+g1bab564.d20181002 Since copytree() is called recursively, the callable will be called once for each directory that is copied. It

path.py, Release 11.4.2.dev11+g1bab564.d20181002

Nname (path.Path attribute), 10namebase (path.Path attribute), 11normcase() (path.Path method), 11normpath() (path.Path method), 11

Oopen() (path.Path method), 11owner (path.Path attribute), 11

Pparent (path.Path attribute), 11Path (class in path), 3path (module), 3pathconf() (path.Path method), 11

Rread_hash() (path.Path method), 11read_hexhash() (path.Path method), 11read_md5() (path.Path method), 11readlink() (path.Path method), 12readlinkabs() (path.Path method), 12realpath() (path.Path method), 12relpath() (path.Path method), 12relpathto() (path.Path method), 12remove() (path.Path method), 12remove_p() (path.Path method), 12removedirs() (path.Path method), 12removedirs_p() (path.Path method), 12rename() (path.Path method), 12renames() (path.Path method), 13rmdir() (path.Path method), 13rmdir_p() (path.Path method), 13rmtree() (path.Path method), 13rmtree_p() (path.Path method), 13

Ssamefile() (path.Path method), 13size (path.Path attribute), 13special (path.Path attribute), 13splitall() (path.Path method), 13splitdrive() (path.Path method), 13splitext() (path.Path method), 13splitpath() (path.Path method), 14splitunc() (path.Path method), 14stat() (path.Path method), 14statvfs() (path.Path method), 14stem (path.Path attribute), 14stripext() (path.Path method), 14symlink() (path.Path method), 14

TTempDir (class in path), 17

text() (path.Path method), 14touch() (path.Path method), 14

Uuncshare (path.Path attribute), 14unlink() (path.Path method), 15unlink_p() (path.Path method), 15using_module() (path.Path class method), 15utime() (path.Path method), 15

Wwalk() (path.Path method), 15walkdirs() (path.Path method), 15walkfiles() (path.Path method), 15with_suffix() (path.Path method), 15write_bytes() (path.Path method), 15write_lines() (path.Path method), 15write_text() (path.Path method), 16

34 Index