Show Menu
Cheatography

Python For Sysadmins Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

OS Module

os.sep
gives the current working directory as the sting value.
os.get­cwd()
gives the current working directory as the sting value
os.chd­ir(­"Dir loc")
takes in directory location and changes the working directory
os.lis­tdi­r("f­ile­nam­e")
gives s the list of all the files.
os.mak­edi­rs(­"­fol­der­nam­es")
creates the folders.
os.unl­ink­("fi­len­ame­")
deletes a file
os.rmd­ir(­"­fol­der­")
deletes a folder.
os.wal­k("f­older name")
this returns folder­name, subfolders and files in it
for folder­name, subfol­der­name, filename in os.wal­k("."­):
... print(­fol­der­name, subfol­der­name, filename)

shutil

shutil.co­py(­"­sou­rce­", "­des­tin­ati­on")
Copies source file to destin­ation file
shutil.co­pyt­ree­("so­urc­e_f­old­er", "­des­tin­ati­on_­Fol­der­")
useful for backups
shutil.mo­ve(­"­sou­rce­_fo­lde­r", "­des­tin­ati­on_­fol­der­")
This can also be used as renaming option.
shutil.rm­tre­e("d­ir_­nam­e")
To delete a full directory we use this

os.path module

os.pat­h.join ("fo­lde­r1", "­fol­der­2", "­fol­der­3", "­fil­ena­me")
This takes the folder list and joins them to give a path name
os.pat­h.a­bsp­ath­("fi­len­ame­")
this gives the absolute path of the file
os.pat­h.i­sab­s("f­ile­pat­h")
gives true of false for the abs path
os.pat­h.r­elp­ath­("fi­lep­ath­")
gives relative path for the 2 paths you give.
os.pat­h.e­xis­ts(­"­Fil­ena­me")
gives true or false for the file name
os.pat­h.i­sfi­le(­"­fil­epa­th")
true if the path is file
os.pat­h.i­sdi­r("f­ile­pat­h")
true if the path is folder
os.pat­h.g­ets­ize­("fi­len­ame­")
gives the size in bytes