Show Menu

Path Cheat Sheet - Python Cheat Sheet by

Cheat Sheet for Path @ Documentation Referenced:

Directory Commands

parent, os.pat­h.d­irn­ame()
Return the current working directory as a path object.
dirs(args, *kwargs)
List of this direct­ory’s subdir­ect­ories. The elements of the list are Path objects. This does not walk recurs­ively into subdir­ect­ories (but see walkdi­rs()). Accepts parameters to listdir().
os.pat­h.e­xists() Return True if path refers to an existing path or an open file descri­ptor. Returns False for broken symbolic links or missing permis­sions
property drive
The drive specifier, for example 'C:'.
Clean up a filename by calling expand­vars(), expand­user(), and normpath() on it.
Return the argument with an initial component of ~ or ~user replaced by that user’s home directory.
Return the argument with enviro­nment variables expanded. Substrings of the form $name or ${name} are replaced by the value of enviro­nment variable name. Bad variables are left unchanged.
property ext
The file extension, for example '.py'.
files(args, *kwargs)
List of the files in self. The elements of the list are Path objects. This does not walk into subdir­ect­ories (see walkfi­les()). Accepts parameters to listdir().
fnmatc­h(p­attern, normca­se=­None)
Return True if matches the given pattern. pattern - A filename pattern with wildcards, for example '*.py'. normcase - (optional) A function used to normalize the pattern and filename before matching.
Return a list of Path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, Path('­/us­ers­').g­lob('/bin/') returns a list of all the files users have in their bin direct­ories.
Return the name of the owner of this file or directory. Follow symbolic links.
Return the time of last access of path.
Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change
Return the size, in bytes, of path.
Return the time of last modifi­cation of path.
Return an iterator of Path objects that match the pattern. pattern - a path relative to this directory, with wildcards.
in_pla­ce(­mod­e='r', buffer­ing=-1, encodi­ng=­None, errors­=None, newlin­e=None, backup­_ex­ten­sio­n=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. A ValueError is raised on invalid modes.
Return True if path is an absolute pathname. On Unix, that means it begins with a slash
Return True if path is an existing directory
Return True if path is an existing regular file.
Return True if path refers to an existing directory entry that is a symbolic link.
Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted

Creation Commands

walk(m­atc­h=None, errors­='s­trict')
Iterator over files and subdirs, recurs­ively. The iterator yields Path objects naming each child item of this directory and its descen­dants.
Create a symbolic link at newlink, pointing here. default = cwd
text(e­nco­din­g=None, errors­='s­trict')
Legacy function to read text. Converts all newline sequences to \n.
Set the access­/mo­dified times of this file to the current time. Create the file if it does not exist.
Remove (delete) the file path.
Like remove(), but does not raise an exception if the file does not exist.
classm­ethod using_­mod­ule­(mo­dule)
utime(args, *kwargs)
Set the access and modified times of this file.
walkdi­rs(­*args, **kwargs)
Iterator over subdirs, recurs­ively.
walkfi­les­(*args, **kwargs)
Iterator over files, recurs­ively.
Return a new path with the file suffix changed (or added, if none)
write_­byt­es(­bytes, append­=False)
Open this file and write the given bytes to it.
write_­lin­es(­lines, encodi­ng=­None, errors­='s­trict', linese­p=_­def­aul­t_l­inesep, append­=False)
Write the given lines of text to this file.
write_­tex­t(text, encodi­ng=­None, errors­='s­trict', linese­p=o­s.l­inesep, append­=False)
Write the given text to this file.
class path.T­empDir(args, *kwargs)
A temporary directory via tempfi­le.m­kd­temp(), and constr­ucted with the same parameters that you can use as a context manager.

Directory Manipu­lation Commmands

Join one or more path segments intell­ige­ntly. The return value is the concat­enation of path and all members of *paths, with exactly one directory separator following each non-empty part, except the last. That is, the result will only end in a separator if the last part is either empty or ends in a separator.
lines(­enc­odi­ng=­None, errors­=None, retain­=True)
Open this file, read all lines, return them in a list.
Create a hard link at newpath, pointing to this file.
List of items in this directory.
Like stat(), but do not follow symbolic links.
Recursive directory creation function. Like mkdir(), but makes all interm­edi­ate­-level direct­ories needed to contain the leaf directory.
Like makedi­rs(), but does not raise an exception if the directory already exists.
merge_­tre­e(dst, symlin­ks=­False, *, copy_f­unc­tio­n=s­hut­il.c­opy2, ignore­=lambda dir, contents: ...)
Copy entire contents of self to dst, overwr­iting existing contents in dst with those in self. Pass symlin­ks=True to copy symbolic links as links. Accepts a copy_f­unc­tion, similar to copytree.
Create a directory named path with numeric mode mode.
Like mkdir(), but does not raise an exception if the directory already exists.
module = <module 'posix­path' (froze­n)>
The path module to use for path operat­ions.
move(dst, copy_f­unc­tio­n=c­opy2)
Recurs­ively move a file or directory to another location. This is similar to the Unix “mv” command. Return the file or direct­ory’s destin­ation.
property mtime
Last modified time of the file.
property name
The name of this file or directory without the full path.
Normalize the case of a pathname.
Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipu­lation may change the meaning of a path that contains
open(args, *kwargs)
Open this file and return a corres­ponding file object.
property owner
Name of the owner of this file or directory.
property parent
This path’s parent directory, as a new Path object.
Path('­/fo­o/b­ar/­baz­').p­arts() -> (Path(­'/'), 'foo', 'bar', 'baz')
Return system config­uration inform­ation relevant to a named file

class path.Path - represents filesystem path

Return a normalized absolu­tized version of the pathname path.
normpa­th(­joi­n(o­s.g­etc­wd(), path))
access­(*args, **kwargs)
Return does the real user have access to this path.
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split().
Open this file, read all bytes, return them as a string.
Change the current working directory to path.
chown(­uid=-1, gid=-1)
Change the owner and group by names or numbers.
Change the root directory of the current process to path.
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. Any argument you pass after size will be passed to open().
copy(dst, *, follow­_sy­mli­nks­=True)
Copy data and mode bits (“cp src dst”). Return the file’s destin­ation. The destin­ation may be a directory.
copy2(dst, *, follow­_sy­mli­nks­=True)
Copy data and metadata. Return the file’s destin­ation. Metadata is copied with copyst­at(). Please see the copystat function for more inform­ation.
copyfi­le(dst, *, follow­_sy­mli­nks­=True)
Copy data from src to dst in the most efficient way possible.
copymo­de(dst, *, follow­_sy­mli­nks­=True)
Copy mode bits from src to dst.
copyst­at(dst, *, follow­_sy­mli­nks­=True)
Copy file metadata. Copy the permission bits, last access time, last modifi­cation time, and flags from src to dst.
copytr­ee(dst, symlin­ks=­False, ignore­=None, copy_f­unc­tio­n=c­opy2, ignore­_da­ngl­ing­_sy­mli­nks­=False, dirs_e­xis­t_o­k=F­alse)
Recurs­ively copy a directory tree and return the destin­ation directory. If except­ion(s) occur, an Error is raised with a list of reasons.
property ctime
Creation time of the file.

Remove Change Commmands

Remove (delete) the file path. Raises Error if Directory or FileNo­tFound.
Like remove(), but does not raise an exception if the file does not exist.
Remove direct­ories recurs­ively.
Like remove­dirs(), but does not raise an exception if the directory is not empty or does not exist.
Rename the file or directory src to dst.
Recursive directory or file renaming function. Works like rename(), except creation of any interm­ediate direct­ories needed to make the new pathname good is attempted first.
Like rmdir(), but does not raise an exception if the directory is not empty or does not exist.
rmtree­(ig­nor­e_e­rro­rs=­False, onerro­r=None, *, dir_fd­=None)
Recurs­ively delete a directory tree.
Like rmtree(), but does not raise an exception if the directory does not exist.
Return True if both pathname arguments refer to the same file or directory.
property size
Size of the file, in bytes.
special = functo­­rti­al(­<class 'path.S­pe­cia­lRe­sol­ver­'>, <class 'path.P­at­h'>)
Return a list of the path components in this path.
Return two-tuple of .drive and rest without drive.
Return two-tuple of .strip­ext() and .ext.
Return two-tuple of .parent, .name.
Perform a stat() system call on this path.
Perform a statvfs() system call on this path. f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid.
property stem
The same as name(), but with one file extension stripped off.
Remove one file extension from the path.

Read Commands

Return the contents of this file as bytes.
Calculate given hash for this file.
Calculate given hash for this file, returning hexdigest.
Calculate the md5 hash for this file.
read_t­ext­(en­cod­ing­=None, errors­=None)
Open this file, read it in, return the content as a string. Optional parameters are passed to open().
Return the path to which this symbolic link points. The result may be an absolute or a relative path.
Return the path to which this symbolic link points.
Return this path as a relative path, based from start, which defaults to the current working directory.
Return a relative path from self to dest.


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter