Show Menu
Cheatography

Path Cheat Sheet - Python Cheat Sheet by

Cheat Sheet for Path @ https://github.com/jaraco/path Documentation Referenced: https://path.readthedocs.io/en/latest/api.html

Directory Commands

dirname()
parent, os.pat­h.d­irn­ame()
classm­ethod
getcwd()
Return the current working directory as a path object.
os.get­cwd()
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().
exists()
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:'.
expand()
Clean up a filename by calling expand­vars(), expand­user(), and normpath() on it.
expand­user()
Return the argument with an initial component of or user replaced by that user’s home directory.
expand­vars()
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 self.name 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.
glob(p­attern)
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.
get_ow­ner()
Return the name of the owner of this file or directory. Follow symbolic links.
getatime()
Return the time of last access of path.
getctime()
Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change
getsize()
Return the size, in bytes, of path.
getmtime()
Return the time of last modifi­cation of path.
iglob(­pat­tern)
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.
isabs()
Return True if path is an absolute pathname. On Unix, that means it begins with a slash
isdir()
Return True if path is an existing directory
isfile()
Return True if path is an existing regular file.
islink()
Return True if path refers to an existing directory entry that is a symbolic link.
ismount()
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.
symlin­k(n­ewl­ink­=None)
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.
touch()
Set the access­/mo­dified times of this file to the current time. Create the file if it does not exist.
unlink()
Remove (delete) the file path.
os.rem­ove()
unlink_p()
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.
with_s­uff­ix(­suffix)
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

joinpa­th(­*ot­hers)
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.
link(n­ewpath)
Create a hard link at newpath, pointing to this file.
listdi­r(m­atc­h=None)
List of items in this directory.
lstat()
Like stat(), but do not follow symbolic links.
makedi­rs(­mod­e=0­o777)
Recursive directory creation function. Like mkdir(), but makes all interm­edi­ate­-level direct­ories needed to contain the leaf directory.
makedi­rs_­p(m­ode­=0o777)
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.
mkdir(­mod­e=0­o777)
Create a directory named path with numeric mode mode.
mkdir_­p(m­ode­=0o777)
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.
basename()
normcase()
Normalize the case of a pathname.
normpath()
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.
parts()
Path('­/fo­o/b­ar/­baz­').p­arts() -> (Path(­'/'), 'foo', 'bar', 'baz')
pathco­nf(­name)
Return system config­uration inform­ation relevant to a named file

class path.Path - represents filesystem path

abspath()
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.
os.acc­ess()
basename()
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split().
bytes()
Open this file, read all bytes, return them as a string.
cd()
os.chd­ir(­path)
Change the current working directory to path.
chdir()
os.chd­ir(­path)
chown(­uid=-1, gid=-1)
Change the owner and group by names or numbers.
chroot()
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()
Remove (delete) the file path. Raises Error if Directory or FileNo­tFound.
remove_p()
Like remove(), but does not raise an exception if the file does not exist.
remove­dirs()
Remove direct­ories recurs­ively.
remove­dir­s_p()
Like remove­dirs(), but does not raise an exception if the directory is not empty or does not exist.
rename­(new)
Rename the file or directory src to dst.
rename­s(new)
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.
rmdir()
os.rmdir()
rmdir_p()
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.
rmtree_p()
Like rmtree(), but does not raise an exception if the directory does not exist.
samefi­le(­other)
Return True if both pathname arguments refer to the same file or directory.
property size
Size of the file, in bytes.
special = functo­ols.pa­rti­al(­<class 'path.S­pe­cia­lRe­sol­ver­'>, <class 'path.P­at­h'>)
splitall()
Return a list of the path components in this path.
splitd­rive()
Return two-tuple of .drive and rest without drive.
splitext()
Return two-tuple of .strip­ext() and .ext.
splitp­ath()
Return two-tuple of .parent, .name.
stat()
Perform a stat() system call on this path.
statvfs()
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.
stripext()
Remove one file extension from the path.

Read Commands

read_b­ytes()
Return the contents of this file as bytes.
read_h­ash­(ha­sh_­name)
Calculate given hash for this file.
read_h­exh­ash­(ha­sh_­name)
Calculate given hash for this file, returning hexdigest.
read_md5()
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().
readlink()
Return the path to which this symbolic link points. The result may be an absolute or a relative path.
readli­nkabs()
Return the path to which this symbolic link points.
realpath()
os.pat­h.r­eal­path()
relpat­h(s­tar­t='.')
Return this path as a relative path, based from start, which defaults to the current working directory.
relpat­hto­(dest)
Return a relative path from self to dest.
   
 

Comments

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