class documentation

I am a path on the filesystem that only permits 'downwards' access.

Instantiate me with a pathname (for example, FilePath('/home/myuser/public_html')) and I will attempt to only provide access to files which reside inside that path. I may be a path to a file, a directory, or a file which does not exist.

The correct way to use me is to instantiate me, and then do ALL filesystem access through me. In other words, do not import the 'os' module; if you need to open a file, call my 'open' method. If you need to list a directory, call my 'path' method.

Even if you pass me a relative path, I will convert that to an absolute path internally.

The type of path when instantiating decides the mode of the FilePath. That is, FilePath(b"/") will return a bytes mode FilePath, and FilePath(u"/") will return a unicode mode FilePath. FilePath("/") will return a bytes mode FilePath on Python 2, and a unicode mode FilePath on Python 3.

Methods that return a new FilePath use the type of the given subpath to decide its mode. For example, FilePath(b"/").child(u"tmp") will return a unicode mode FilePath.

Method __cmp__ Undocumented
Method __eq__ Undocumented
Method __ge__ Undocumented
Method __getstate__ Support serialization by discarding cached os.stat results and returning everything else.
Method __gt__ Undocumented
Method __init__ Convert a path string to an absolute path if necessary and initialize the FilePath with the result.
Method __le__ Undocumented
Method __lt__ Undocumented
Method __ne__ Undocumented
Method __repr__ Undocumented
Method asBytesMode Return this FilePath in bytes-mode.
Method asTextMode Return this FilePath in unicode-mode.
Method basename Retrieve the final component of the file path's path (everything after the final path separator).
Method changed Clear any cached information about the state of this path on disk.
Method child Create and return a new FilePath representing a path contained by self.
Method childSearchPreauth Return my first existing child with a name in paths.
Method chmod Changes the permissions on self, if possible. Propagates errors from os.chmod up.
Method clonePath Make an object of the same type as this FilePath, but with path of path.
Method copyTo Copies self to destination.
Method create Exclusively create a file, only if this file previously did not exist.
Method createDirectory Create the directory the FilePath refers to.
Method descendant Retrieve a child or child's child of this path.
Method dirname Retrieve all of the components of the FilePath's path except the last one (everything up to the final path separator).
Method exists Check if this FilePath exists.
Method getAccessTime Retrieve the time that this file was last accessed.
Method getDevice Retrieves the device containing the file. The inode number and device number together uniquely identify the file, but the device number is not necessarily consistent across reboots or system crashes.
Method getGroupID Returns the group ID of the file.
Method getInodeNumber Retrieve the file serial number, also called inode number, which distinguishes this file from all other files on the same device.
Method getModificationTime Retrieve the time of last access from this file.
Method getNumberOfHardLinks Retrieves the number of hard links to the file.
Method getPermissions Returns the permissions of the file. Should also work on Windows, however, those permissions may not be what is expected in Windows.
Method getsize Retrieve the size of this file in bytes.
Method getStatusChangeTime Retrieve the time of the last status change for this file.
Method getUserID Returns the user ID of the file's owner.
Method globChildren Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern.
Method isabs Check if this FilePath refers to an absolute path.
Method isBlockDevice Returns whether the underlying path is a block device.
Method isdir Check if this FilePath refers to a directory.
Method isfile Check if this file path refers to a regular file.
Method islink Check if this FilePath points to a symbolic link.
Method isSocket Returns whether the underlying path is a socket.
Method linkTo Creates a symlink to self to at the path in the FilePath linkFilePath.
Method listdir List the base names of the direct children of this FilePath.
Method makedirs Create all directories not yet existing in path segments, using os.makedirs.
Method moveTo Move self to destination - basically renaming self to whatever destination is named.
Method open Open this file using mode or for writing if alwaysCreate is True.
Method parent A file path for the directory containing the file at this file path.
Method parents Retrieve an iterator of all the ancestors of this path.
Method preauthChild Use me if path might have slashes in it, but you know they're safe.
Method realpath Returns the absolute target as a FilePath if self is a link, self otherwise.
Method remove Removes the file or directory that is represented by self. If self.path is a directory, recursively remove all its children before removing the directory. If it's a file or link, just delete it.
Method requireCreate Sets the alwaysCreate variable.
Method restat Re-calculate cached effects of 'stat'. To refresh information on this path after you know the filesystem may have changed, call this method.
Method setContent Replace the file at this path with a new file that contains the given bytes, trying to avoid data-loss in the meanwhile.
Method sibling Return a FilePath with the same directory as this instance but with a basename of path.
Method siblingExtension Attempt to return a path with my name, given the extension at ext.
Method siblingExtensionSearch Attempt to return a path with my name, given multiple possible extensions.
Method splitext Split the file path into a pair (root, ext) such that root + ext == path.
Method temporarySibling Construct a path referring to a sibling of this path.
Method touch Updates the access and last modification times of the file at this file path to the current time. Also creates the file if it does not already exist.
Instance Variable alwaysCreate When opening this file, only succeed if the file does not already exist.
Instance Variable path The path from which 'downward' traversal is permitted.
Property sep Return a filesystem separator.
Method _asBytesPath Return the path of this FilePath as bytes.
Method _asTextPath Return the path of this FilePath as text.
Method _getPathAsSameTypeAs If pattern is bytes, return FilePath.path as bytes. Otherwise, return FilePath.path as unicode.
Class Variable _chunkSize Undocumented
Instance Variable _statinfo Undocumented

Inherited from AbstractFilePath:

Method __hash__ Hash the same as another AbstractFilePath with the same path as mine.
Method children List the children of this path object.
Method getatime Deprecated. Use getAccessTime instead.
Method getContent Retrieve the contents of the file at this path.
Method getctime Deprecated. Use getStatusChangeTime instead.
Method getmtime Deprecated. Use getModificationTime instead.
Method segmentsFrom Return a list of segments between a child and its ancestor.
Method walk Yield myself, then each of my children, and each of those children's children in turn.
Type Variable Selfish Undocumented
def __cmp__(self, other: object) -> int: (source)

Undocumented

def __eq__(self, other: object) -> bool: (source)

Undocumented

def __ge__(self, other: object) -> bool: (source)

Undocumented

def __getstate__(self) -> Dict[str, object]: (source)

Support serialization by discarding cached os.stat results and returning everything else.

def __gt__(self, other: object) -> bool: (source)

Undocumented

def __init__(self, path: AnyStr, alwaysCreate: bool = False): (source)

Convert a path string to an absolute path if necessary and initialize the FilePath with the result.

def __le__(self, other: object) -> bool: (source)

Undocumented

def __lt__(self, other: object) -> bool: (source)

Undocumented

def __ne__(self, other: object) -> bool: (source)

Undocumented

def __repr__(self) -> str: (source)

Undocumented

def asBytesMode(self, encoding: Optional[str] = None) -> FilePath[bytes]: (source)

Return this FilePath in bytes-mode.

Parameters
encoding:Optional[str]The encoding to use if coercing to bytes. If none is given, sys.getfilesystemencoding is used.
Returns
FilePath[bytes]bytes mode FilePath
def asTextMode(self, encoding: Optional[str] = None) -> FilePath[str]: (source)

Return this FilePath in unicode-mode.

Parameters
encoding:Optional[str]The encoding to use if coercing to unicode. If none is given, sys.getfilesystemencoding is used.
Returns
FilePath[str]unicode mode FilePath
def basename(self) -> AnyStr: (source)

Retrieve the final component of the file path's path (everything after the final path separator).

Returns
the same type as this FilePath's path attributeThe final component of the FilePath's path (Everything after the final path separator).
def changed(self): (source)

Clear any cached information about the state of this path on disk.

Present Since
10.1.0
def child(self, path: OtherAnyStr) -> FilePath[OtherAnyStr]: (source)

Create and return a new FilePath representing a path contained by self.

Parameters
path:bytes or unicodeThe base name of the new FilePath. If this contains directory separators or parent references it will be rejected.
Returns
FilePath with a mode equal to the type of path.The child path.
Raises
InsecurePathIf the result of combining this path with path would result in a path which is not a direct child of this path.
def childSearchPreauth(self, *paths: OtherAnyStr) -> Optional[FilePath[OtherAnyStr]]: (source)

Return my first existing child with a name in paths.

paths is expected to be a list of *pre-secured* path fragments; in most cases this will be specified by a system administrator and not an arbitrary user.

If no appropriately-named children exist, this will return None.

Returns
None or FilePathNone or the child path.
def chmod(self, mode: int): (source)

Changes the permissions on self, if possible. Propagates errors from os.chmod up.

Parameters
mode:intinteger representing the new permissions desired (same as the command line chmod)
def clonePath(self, path: OtherAnyStr, alwaysCreate: bool = False) -> FilePath[OtherAnyStr]: (source)

Make an object of the same type as this FilePath, but with path of path.

def copyTo(self, destination: FilePath[OtherAnyStr], followLinks: bool = True): (source)

Copies self to destination.

If self doesn't exist, an OSError is raised.

If self is a directory, this method copies its children (but not itself) recursively to destination - if destination does not exist as a directory, this method creates it. If destination is a file, an IOError will be raised.

If self is a file, this method copies it to destination. If destination is a file, this method overwrites it. If destination is a directory, an IOError will be raised.

If self is a link (and followLinks is False), self will be copied over as a new symlink with the same target as returned by os.readlink. That means that if it is absolute, both the old and new symlink will link to the same thing. If it's relative, then perhaps not (and it's also possible that this relative link will be broken).

File/directory permissions and ownership will NOT be copied over.

If followLinks is True, symlinks are followed so that they're treated as their targets. In other words, if self is a link, the link's target will be copied. If destination is a link, self will be copied to the destination's target (the actual destination will be destination's target). Symlinks under self (if self is a directory) will be followed and its target's children be copied recursively.

If followLinks is False, symlinks will be copied over as symlinks.

Parameters
destination:FilePath[OtherAnyStr]the destination (a FilePath) to which self should be copied
followLinks:boolwhether symlinks in self should be treated as links or as their targets
def create(self) -> IO[bytes]: (source)

Exclusively create a file, only if this file previously did not exist.

Returns
IO[bytes]A file-like object opened from this path.
def createDirectory(self): (source)

Create the directory the FilePath refers to.

Raises
OSErrorIf the directory cannot be created.
See Also
makedirs
def descendant(self, segments: Sequence[OtherAnyStr]) -> FilePath[OtherAnyStr]: (source)

Retrieve a child or child's child of this path.

Parameters
segments:Sequence[OtherAnyStr]A sequence of path segments as str instances.
Returns
FilePath[OtherAnyStr]A FilePath constructed by looking up the segments[0] child of this path, the segments[1] child of that path, and so on.
Present Since
10.2
Note
for type-checking, subclasses should override this signature to make it clear that it returns the subclass and not AbstractFilePath.
def dirname(self) -> AnyStr: (source)

Retrieve all of the components of the FilePath's path except the last one (everything up to the final path separator).

Returns
the same type as this FilePath's path attributeAll of the components of the FilePath's path except the last one (everything up to the final path separator).
def exists(self) -> bool: (source)

Check if this FilePath exists.

Returns
boolTrue if the stats of path can be retrieved successfully, False in the other cases.
def getAccessTime(self) -> float: (source)

Retrieve the time that this file was last accessed.

Returns
floata number of seconds from the epoch.
def getDevice(self) -> int: (source)

Retrieves the device containing the file. The inode number and device number together uniquely identify the file, but the device number is not necessarily consistent across reboots or system crashes.

Returns
inta number representing the device
Raises
NotImplementedErrorif the platform is Windows, since the device number would be 0 for all partitions on a Windows platform
Present Since
11.0
def getGroupID(self) -> int: (source)

Returns the group ID of the file.

Returns
intthe group ID of the file
Raises
NotImplementedErrorif the platform is Windows, since the GID is always 0 on windows
Present Since
11.0
def getInodeNumber(self) -> int: (source)

Retrieve the file serial number, also called inode number, which distinguishes this file from all other files on the same device.

Returns
inta number representing the file serial number
Raises
NotImplementedErrorif the platform is Windows, since the inode number would be a dummy value for all files in Windows
Present Since
11.0
def getModificationTime(self) -> float: (source)

Retrieve the time of last access from this file.

Returns
floata number of seconds from the epoch.
def getNumberOfHardLinks(self) -> int: (source)

Retrieves the number of hard links to the file.

This count keeps track of how many directories have entries for this file. If the count is ever decremented to zero then the file itself is discarded as soon as no process still holds it open. Symbolic links are not counted in the total.

Returns
intthe number of hard links to the file
Raises
NotImplementedErrorif the platform is Windows, since Windows doesn't maintain a link count for directories, and os.stat does not set st_nlink on Windows anyway.
Present Since
11.0
def getPermissions(self) -> Permissions: (source)

Returns the permissions of the file. Should also work on Windows, however, those permissions may not be what is expected in Windows.

Returns
Permissionsthe permissions for the file
Present Since
11.1
def getsize(self) -> int: (source)

Retrieve the size of this file in bytes.

Returns
intThe size of the file at this file path in bytes.
Raises
Exceptionif the size cannot be obtained.
def getStatusChangeTime(self) -> float: (source)

Retrieve the time of the last status change for this file.

Returns
floata number of seconds from the epoch.
def getUserID(self) -> int: (source)

Returns the user ID of the file's owner.

Returns
intthe user ID of the file's owner
Raises
NotImplementedErrorif the platform is Windows, since the UID is always 0 on Windows
Present Since
11.0
def globChildren(self, pattern: OtherAnyStr) -> List[FilePath[OtherAnyStr]]: (source)

Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern.

Parameters
pattern:unicode or bytesA glob pattern to use to match child paths.
Returns
list of FilePath, with the mode of pattern's typeA list of matching children.
def isabs(self) -> bool: (source)

Check if this FilePath refers to an absolute path.

This always returns True.

Returns
boolTrue, always.
def isBlockDevice(self) -> bool: (source)

Returns whether the underlying path is a block device.

Returns
boolTrue if it is a block device, False otherwise
Present Since
11.1
def isdir(self) -> bool: (source)

Check if this FilePath refers to a directory.

Returns
boolTrue if this FilePath refers to a directory, False otherwise.
def isfile(self) -> bool: (source)

Check if this file path refers to a regular file.

Returns
boolTrue if this FilePath points to a regular file (not a directory, socket, named pipe, etc), False otherwise.
def islink(self) -> bool: (source)

Check if this FilePath points to a symbolic link.

Returns
boolTrue if this FilePath points to a symbolic link, False otherwise.
def isSocket(self) -> bool: (source)

Returns whether the underlying path is a socket.

Returns
boolTrue if it is a socket, False otherwise
Present Since
11.1
def linkTo(self, linkFilePath: FilePath[AnyStr]): (source)

Creates a symlink to self to at the path in the FilePath linkFilePath.

Only works on posix systems due to its dependence on os.symlink. Propagates OSErrors up from os.symlink if linkFilePath.parent() does not exist, or linkFilePath already exists.

Parameters
linkFilePath:FilePatha FilePath representing the link to be created.
def listdir(self) -> List[AnyStr]: (source)

List the base names of the direct children of this FilePath.

Returns
listA list of bytes/unicode giving the names of the contents of the directory this FilePath refers to. These names are relative to this FilePath.
Raises
OSErrorAny exception the platform os.listdir implementation may raise.
def makedirs(self, ignoreExistingDirectory: bool = False): (source)

Create all directories not yet existing in path segments, using os.makedirs.

Parameters
ignoreExistingDirectory:boolDon't raise OSError if directory already exists.
Returns
None
def moveTo(self, destination: FilePath[OtherAnyStr], followLinks: bool = True): (source)

Move self to destination - basically renaming self to whatever destination is named.

If destination is an already-existing directory, moves all children to destination if destination is empty. If destination is a non-empty directory, or destination is a file, an OSError will be raised.

If moving between filesystems, self needs to be copied, and everything that applies to copyTo applies to moveTo.

Parameters
destination:FilePath[OtherAnyStr]the destination (a FilePath) to which self should be copied
followLinks:boolwhether symlinks in self should be treated as links or as their targets (only applicable when moving between filesystems)
def open(self, mode: FileMode = 'r') -> IO[bytes]: (source)

Open this file using mode or for writing if alwaysCreate is True.

In all cases the file is opened in binary mode, so it is not necessary to include "b" in mode.

Parameters
mode:FileModeThe mode to open the file in. Default is "r".
Returns
IO[bytes]An open file-like object.
Raises
AssertionErrorIf "a" is included in the mode and alwaysCreate is True.
def parent(self) -> FilePath[AnyStr]: (source)

A file path for the directory containing the file at this file path.

Returns
FilePathA FilePath representing the path which directly contains this FilePath.
def parents(self) -> Iterable[FilePath[AnyStr]]: (source)

Retrieve an iterator of all the ancestors of this path.

Returns
Iterable[FilePath[AnyStr]]an iterator of all the ancestors of this path, from the most recent (its immediate parent) to the root of its filesystem.
def preauthChild(self, path: OtherAnyStr) -> FilePath[OtherAnyStr]: (source)

Use me if path might have slashes in it, but you know they're safe.

Parameters
path:bytes or unicodeA relative path (ie, a path not starting with "/") which will be interpreted as a child or descendant of this path.
Returns
FilePath with a mode equal to the type of path.The child path.
def realpath(self) -> FilePath[AnyStr]: (source)

Returns the absolute target as a FilePath if self is a link, self otherwise.

The absolute link is the ultimate file or directory the link refers to (for instance, if the link refers to another link, and another...). If the filesystem does not support symlinks, or if the link is cyclical, raises a LinkError.

Behaves like os.path.realpath in that it does not resolve link names in the middle (ex. /x/y/z, y is a link to w - realpath on z will return /x/y/z, not /x/w/z).

Returns
FilePathFilePath of the target path.
Raises
LinkErrorif links are not supported or links are cyclical.
def remove(self): (source)

Removes the file or directory that is represented by self. If self.path is a directory, recursively remove all its children before removing the directory. If it's a file or link, just delete it.

def requireCreate(self, val: bool = True): (source)

Sets the alwaysCreate variable.

Parameters
val:boolTrue or False, indicating whether opening this path will be required to create the file or not.
Returns
None
def restat(self, reraise: bool = True): (source)

Re-calculate cached effects of 'stat'. To refresh information on this path after you know the filesystem may have changed, call this method.

Parameters
reraise:boola boolean. If true, re-raise exceptions from os.stat; otherwise, mark this path as not existing, and remove any cached stat information.
Raises
ExceptionIf reraise is True and an exception occurs while reloading metadata.
def setContent(self, content: bytes, ext: Union[str, bytes] = '.new'): (source)

Replace the file at this path with a new file that contains the given bytes, trying to avoid data-loss in the meanwhile.

On UNIX-like platforms, this method does its best to ensure that by the time this method returns, either the old contents or the new contents of the file will be present at this path for subsequent readers regardless of premature device removal, program crash, or power loss, making the following assumptions:

  • your filesystem is journaled (i.e. your filesystem will not itself lose data due to power loss)
  • your filesystem's rename() is atomic
  • your filesystem will not discard new data while preserving new metadata (see http://mjg59.livejournal.com/108257.html for more detail)

On most versions of Windows there is no atomic rename() (see http://bit.ly/win32-overwrite for more information), so this method is slightly less helpful. There is a small window where the file at this path may be deleted before the new file is moved to replace it: however, the new file will be fully written and flushed beforehand so in the unlikely event that there is a crash at that point, it should be possible for the user to manually recover the new version of their data. In the future, Twisted will support atomic file moves on those versions of Windows which do support them: see Twisted ticket 3004.

This method should be safe for use by multiple concurrent processes, but note that it is not easy to predict which process's contents will ultimately end up on disk if they invoke this method at close to the same time.

Parameters
content:bytesThe desired contents of the file at this path.
ext:bytesAn extension to append to the temporary filename used to store the bytes while they are being written. This can be used to make sure that temporary files can be identified by their suffix, for cleanup in case of crashes.
def sibling(self: _Self, path: OtherAnyStr) -> FilePath[OtherAnyStr]: (source)

Return a FilePath with the same directory as this instance but with a basename of path.

Parameters
path:strThe basename of the FilePath to return.
Returns
FilePathThe sibling path.
Note
for type-checking, subclasses should override this signature to make it clear that it returns the subclass and not AbstractFilePath.
def siblingExtension(self, ext: OtherAnyStr) -> FilePath[OtherAnyStr]: (source)

Attempt to return a path with my name, given the extension at ext.

Parameters
ext:bytes or unicodeFile-extension to search for.
Returns
FilePath with the same mode as the type of ext.The sibling path.
def siblingExtensionSearch(self, *exts: OtherAnyStr) -> Optional[FilePath[OtherAnyStr]]: (source)

Attempt to return a path with my name, given multiple possible extensions.

Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in exts, then if the file referred to by this path exists, self will be returned.

The extension '*' has a magic meaning, which means "any path that begins with self.path + '.' is acceptable".

def splitext(self) -> Tuple[AnyStr, AnyStr]: (source)

Split the file path into a pair (root, ext) such that root + ext == path.

Returns
tupleTuple where the first item is the filename and second item is the file extension. See Python docs for os.path.splitext.
@overload
def temporarySibling(self) -> FilePath[AnyStr]:
@overload
def temporarySibling(self, extension: Optional[OtherAnyStr]) -> FilePath[OtherAnyStr]:
(source)

Construct a path referring to a sibling of this path.

The resulting path will be unpredictable, so that other subprocesses should neither accidentally attempt to refer to the same path before it is created, nor they should other processes be able to guess its name in advance.

Parameters
extension:bytes or unicodeA suffix to append to the created filename. (Note that if you want an extension with a '.' you must include the '.' yourself.)
Returns
FilePath with a mode equal to the type of extensiona path object with the given extension suffix, alwaysCreate set to True.
def touch(self): (source)

Updates the access and last modification times of the file at this file path to the current time. Also creates the file if it does not already exist.

Raises
Exceptionif unable to create or modify the last modification time of the file.
alwaysCreate: bool = (source)

When opening this file, only succeed if the file does not already exist.

The path from which 'downward' traversal is permitted.

Return a filesystem separator.

Returns
The same type as self.path.Undocumented
def _asBytesPath(self, encoding: Optional[str] = None) -> bytes: (source)

Return the path of this FilePath as bytes.

Parameters
encoding:Optional[str]The encoding to use if coercing to bytes. If none is given, sys.getfilesystemencoding is used.
Returns
bytesbytes
def _asTextPath(self, encoding: Optional[str] = None) -> str: (source)

Return the path of this FilePath as text.

Parameters
encoding:Optional[str]The encoding to use if coercing to unicode. If none is given, sys.getfilesystemencoding is used.
Returns
strunicode
def _getPathAsSameTypeAs(self, pattern: OtherAnyStr) -> OtherAnyStr: (source)

If pattern is bytes, return FilePath.path as bytes. Otherwise, return FilePath.path as unicode.

Parameters
pattern:OtherAnyStrThe new element of the path that FilePath.path may need to be coerced to match.
Returns
OtherAnyStrUndocumented
_chunkSize = (source)

Undocumented

_statinfo = (source)

Undocumented