0% found this document useful (0 votes)
2 views241 pages

Python Nemo

Python is a high-level, interpreted, interactive, and object-oriented scripting language that is easy to read and understand. It is popular due to its extensive libraries, documentation, and community support, making it accessible for beginners despite the complexity of some packages. The document also covers fundamental data structures in Python, including lists, dictionaries, sets, tuples, and strings, along with their operations and methods.

Uploaded by

nview360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views241 pages

Python Nemo

Python is a high-level, interpreted, interactive, and object-oriented scripting language that is easy to read and understand. It is popular due to its extensive libraries, documentation, and community support, making it accessible for beginners despite the complexity of some packages. The document also covers fundamental data structures in Python, including lists, dictionaries, sets, tuples, and strings, along with their operations and methods.

Uploaded by

nview360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting


language.
High-level: easy to read and understand
High-level: easy to read and understand
Interpreted: no compilation step
High-level: easy to read and understand
Interpreted: no compilation step
Interactive: can be used as a calculator
High-level: easy to read and understand
Interpreted: no compilation step
Interactive: can be used as a calculator
Object-oriented: supports object-oriented style or procedure-oriented style
Why Python?
Python is extremely popular; which means:
Python is extremely popular; which means:
- Lots of libraries
Python is extremely popular; which means:
- Lots of libraries
- Lots of documentation
Python is extremely popular; which means:
- Lots of libraries
- Lots of documentation
- Lots of support
Python is extremely popular; which means:
- Lots of libraries
- Lots of documentation
- Lots of support
Python is easy to learn, but the packages are not.
List
A list is a collection which is ordered and mutable. Allows duplicate members.
Defining a List
Defining a List
<list> = [<el1>, <el2>, <el3>, ...]
# Or:
<list> = list(<collection>)
Slicing a List
Slicing a List
# <list>[from_inclusive : to_exclusive : ±step]
<list> = <list>[<slice>]
Append to a list
Append to a list
<list>.append(<el>) # Or: <list> += [<el>]
<list>.extend(<collection>) # Or: <list> += <collection>
Sort a list
Sort a list
<list>.sort() # Sorts in ascending order.
<list>.reverse() # Reverses the list in-place.
<list> = sorted(<collection>) # Returns a new sorted list.
<iter> = reversed(<list>) # Returns reversed iterator.
Sum the elements of a list
Sum the elements of a list
sum_of_elements = sum(<collection>)
Sum element wise of two lists
Sum element wise of two lists
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
Sort a list of tuples by the second element
Sort a list of tuples by the second element
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
Flatten a list of lists
Flatten a list of lists
import itertools

flattend_list = list([Link].from_iterable(<list>))
Product of all the elements of a list
Product of all the elements of a list
from operator import mul
from functools import reduce

product_of_elems = reduce(mul, <collection>, 1) # 1 is the initial value


# Or:
product_of_elems = reduce(lambda out, el: out * el, <collection>)
List of all chars is a string
List of all chars is a string
list_of_chars = list(<str>)
Other operations
Other operations
<list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([<int>]) # Removes and returns item at index or from the end.
<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>) # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>) # Removes first occurrence of the item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.
Dictionary
A dictionary is a collection of key-value pairs.
Defining a dictionary
Defining a dictionary
<dict> = {<key>: <value>, <key>: <value>, ...}
# Or:
<dict> = dict(<list_of_tuples> )
# Or:
<dict> = dict(<key>=<value>, <key>=<value>, ...)
# Or:
<dict> = dict(zip(<keys>, <values>))
# Or:
<dict> = [Link](<keys>, <value>) # All keys have the same value.
# Or (Python 3.6+):
<dict> = {<key>: <value> for <key> in <keys>}
Accessing a dictionary
Accessing a dictionary
<value> = <dict>[<key>]
# Or:
<value> = <dict>.get(<key>, <default>)
Adding a key-value pair
Adding a key-value pair
<dict>[<key>] = <value>
Removing a key-value pair
Removing a key-value pair
del <dict>[<key>]
Iterating over a dictionary
Iterating over a dictionary
for <key>, <value> in <dict>.items():
<statement>
Returns set of keys that point to the value
Returns set of keys that point to the value
<set> = {k for k, v in <dict>.items() if v == value}
Returns a dictionary, filtered by keys
Returns a dictionary, filtered by keys
<dict> = {k: v for k, v in <dict>.items() if k in <keys>}
Count elements in a collection
Count elements in a collection
from collections import Counter
<dict> = Counter(<collection>)

# Get the most common elements:


<list> = <dict>.most_common(<int>) # Returns a list of tuples (element, count).
Other operations
Other operations
<dict>.clear() # Removes all items. Also works on list and set.
<dict>.update(<dict2>) # Updates with the key/value pairs from <dict2>, overwriting exis
<dict>.keys() # Returns a view object that displays a list of all the keys in t
<dict>.values() # Returns a view object that displays a list of all the values in
<dict>.items() # Returns a view object that displays a list of all the key/value
Set
Set is an unordered collection of unique elements.
It is mutable, but the elements must be immutable.
Defining a set
Defining a set
<set> = {<el>, <el>, ...}
# Or:
<set> = set(<collection>)
Union between two sets
Union between two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 | set2 # {1, 2, 3, 4, 5}


# Or:
set3 = [Link](set2)
Intersection between two sets
Intersection between two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 & set2 # {3}


# Or:
set3 = [Link](set2)
Subtraction between two sets
Subtraction between two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 - set2 # {1, 2}


# Or:
set3 = [Link](set2)
Symmetric difference between two sets
Symmetric difference between two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 ^ set2 # {1, 2, 4, 5} (elements that are in either set1 or set2, but not both)
# Or:
set3 = set1.symmetric_difference(set2)
Is a set a subset of another set
Is a set a subset of another set
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 <= set2 # False


# Or:
set3 = [Link](set2)
Is a set a superset of another set
Is a set a superset of another set
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set3 = set1 >= set2 # False


# Or:
set3 = [Link](set2)
Is a set disjoint with another set
Is a set disjoint with another set
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Returns True if the set has no elements in common with set2.


set3 = [Link](set2) # False
Adding an element
Adding an element
<set>.add(<el>)
Removing an element (if it exists)
Removing an element (if it exists)
<set>.discard(<el>)
# Or:
<set>.remove(<el>) # Raises KeyError if <el> is not a member.
Using frozenset
Using frozenset
<frozenset> = frozenset(<collection>)

# frozenset is immutable and hashable.


# It can be used as a key in a dictionary or as an element of another set.
# Example
<dict> = {
<frozenset>: <value>
}
Other operations
Other operations
<set>.clear() # Removes all items. Also works on dictionary and list.
Tuple
Defining a tuple
Defining a tuple
<tuple> = (<el>, <el>, ...)
Accessing an element
Accessing an element
<el> = <tuple>[<index>]
Named Tuple
Named Tuple
from collections import namedtuple
<tuple> = namedtuple('<tuple>', ['<field1>', '<field2>', ...])
<tuple> = <tuple>(<value1>, <value2>, ...)

<tuple>.<field1>
<tuple>.<field2>
# Or:
<tuple>[<index>]
Other operations
Other operations
<tuple>.count(<el>) # Returns the number of times <el> appears in the tuple.
<tuple>.index(<el>) # Returns the index of the first occurrence of <el>.
String
Accessing an element
Accessing an element
<el> = <string>[<index>]
Checks if string contains the substring
Checks if string contains the substring
<sub_str> in <str>
# Or:
<str>.find(<sub_str>) != -1 # Returns the index of the first occurrence of <sub_str> or -1 if no
# Or:
<str>.index(<sub_str>) # Returns the index of the first occurrence of <sub_str> or raises V
Check for suffix or prefix
Check for suffix or prefix
<str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
<str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
Remove whitespace
Remove whitespace
<str>.strip() # Removes whitespace from both ends.
<str>.lstrip() # Removes whitespace from the left end.
<str>.rstrip() # Removes whitespace from the right end.
Splitting a string
Splitting a string
<list> = <str>.split(<sep>) # Returns a list of strings after breaking the given string by the s
<list> = <str>.splitlines(keepends=False) # Returns a list of lines in the string, breaking at l
# If keepends is False, the line breaks are not includ
Joining a string
Joining a string
<str> = <sep>.join(<list>) # Returns a string concatenated with the elements of an iterable.
Replacing a string
Replacing a string
<str> = <str>.replace(<old>, <new>, <count>)
# Returns a copy of the string with all occurrences of substring <old> replaced by <new>.
# If the optional argument <count> is given, only the first <count> occurrences are replaced.

<table> = [Link](<x>, <y>)


# <x> is a string specifying the characters you want to replace.
# <y> is a string specifying the characters you want to replace <x> with.

# Or:

<table> = [Link](<dict>)
# Dict is a dictionary mapping characters to be replaced to the characters to replace them with

<str> = <str>.translate(<table>, <deletechars>)


# Returns a copy of the string where all characters occurring in the optional argument <deletech
# and the remaining characters have been mapped through the given translation table, which must
Other operations
Other operations
<string>.count(<el>) # Returns the number of times <el> appears in the string.
<string>.index(<el>) # Returns the index of the first occurrence of <el>.
<string>.capitalize() # Returns a copy of the string with only its first character capi
<string>.lower() # Returns a copy of the string with all the characters converted
<string>.upper() # Returns a copy of the string with all the characters converted
<string>.startswith(<prefix>) # Returns True if the string starts with the specified prefix, ot
<string>.endswith(<suffix>) # Returns True if the
Date and Time
- Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD> classe
- Time and datetime objects can be 'aware' <a>, meaning they have defined timezone, or 'naive' <
- If object is naive, it is presumed to be in the system's timezone.
datetime Constructors
datetime Constructors
<D> = date(year, month, day) # Date object with year, month and day.
<T> = time(hour=0, minute=0, second=0) # Also: `microsecond=0, tzinfo=None, fold=0`
# 'fold=1' means the second pass in case of time jumping
<DT> = datetime(year, month, day, hour=0) # Also: `minute=0, second=0, microsecond=0, tzinfo=Non
<TD> = timedelta(weeks=0, days=0, hours=0) # Also: `minutes=0, seconds=0, microsecond=0`.
# Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
Parse string to datetime
Parse string to datetime
<DT> = [Link](<str>, <format>) # Returns a datetime corresponding to <str> parsed a
<DT> = [Link](<str>) # Returns a datetime corresponding to <str> parsed a
# The ISO 8601 format is YYYY-MM-DDTHH:MM:[Link]
<DT> = [Link](<ordinal>) # Returns a datetime corresponding to the proleptic
# The Gerogian ordinal is the number of days since J
<DT> = [Link](<timestamp>) # Returns a datetime corresponding to the POSIX time
# The POSIX timestamp is the number of seconds since
Get current time/date
Get current time/date
<D/DTn> = D/[Link]() # Current local date or naive datetime.
<DTn> = [Link]() # Naive datetime from current UTC time.
<DTa> = [Link](<tzinfo>) # Aware datetime from current tz time.
Parse datetime to string
Parse datetime to string
<str> = <DT>.strftime(<format>) # Returns a string representing the date and time, controlled by
<str> = <DT>.isoformat() # Returns a string representing the date and time in ISO 8601 fo
<str> = <DT>.ctime() # Returns a string representing the date and time in the format
Arithmetics of datetime
Arithmetics of datetime
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour.
<TD> = <D/DTn> - <D/DTn> # Returns the difference, ignoring time jumps.
<TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object.
<TD> = <TD> * <real> # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>.
<float> = <TD> / <TD> # How many weeks/years there are in TD. Also //.
Get date/time components
Get date/time components
<int> = <DT>.year
<int> = <DT>.month
<int> = <DT>.day
<int> = <DT>.hour
<int> = <DT>.minute
<int> = <DT>.second
<int> = <DT>.microsecond
<int> = <DT>.weekday() # Returns the day of the week as an integer, where Monday is 0 a
<int> = <DT>.isoweekday() # Returns the day of the week as an integer, where Monday is 1 a
<int> = <DT>.toordinal() # Returns the proleptic Gregorian ordinal, where January 1 of ye
<int> = <DT>.timestamp() # Returns the POSIX timestamp as a float.
<int> = <DT>.utcoffset() # Returns the offset of the timezone from UTC as a timedelta obj
<int> = <DT>.dst() # Returns the daylight saving time (DST) adjustment as a timedel
<int> = <DT>.tzname() # Returns the name of the timezone.
Enumerate
What is enumerate?
What is enumerate?
Enumerate is a built-in function of Python.
What is enumerate?
Enumerate is a built-in function of Python.
Enumerate allows us to loop over something and have an automatic counter.
What is enumerate?
Enumerate is a built-in function of Python.
Enumerate allows us to loop over something and have an automatic counter.
Enumerate returns a tuple of the counter and the value of the item at that
counter.
Using enumerate
Using enumerate
for <index>, <el> in enumerate(<collection>):
<code>
Comprehensions
Defining a list
Defining a list
<list> = [<el> for <el> in <collection>]
# Or:
<list> = [<el> for <el> in <collection> if <condition>]
Defining a dictionary
Defining a dictionary
<dict> = {<key>: <value> for <el> in <collection>}
# Or:
<dict> = {<key>: <value> for <el> in <collection> if <condition>}
Defining a set
Defining a set
<set> = {<el> for <el> in <collection>}
# Or:
<set> = {<el> for <el> in <collection> if <condition>}
Functions
Arguments positions inside a function call
Arguments positions inside a function call
func(<positional_args>) # func(0, 0)
func(<keyword_args>) # func(x=0, y=0)
func(<positional_args>, <keyword_args>) # func(0, y=0)
Arguments positions inside a function defintion
Arguments positions inside a function defintion
def func(<nondefault_args>): ... # def func(x, y): ...
def func(<default_args>): ... # def func(x=0, y=0): ...
def func(<nondefault_args>, <default_args>): ... # def func(x, y=0): ...
# Default values are evaluated when function is first encountered in the scope.
# Any mutation of a mutable default value will persist between invocations!
Unpacking argument lists
Unpacking argument lists
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)

# Is the same as:

func(1, 2, x=3, y=4, z=5)


Legal argument combinations for unpacking argument lists
Legal argument combinations for unpacking argument lists
def f(*args): ... # f(1, 2, 3)
def f(x, *args): ... # f(1, 2, 3)
def f(*args, z): ... # f(1, 2, z=3)

def f(**kwargs): ... # f(x=1, y=2, z=3)


def f(x, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)

def f(*args, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(x, *args, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(*args, y, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)

def f(*, x, y, z): ... # f(x=1, y=2, z=3)


def f(x, *, y, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, y, *, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Generators
What is a generator?
What is a generator?
A generator is a function that returns an object (iterator) which we can iterate over
(one value at a time).
What is a generator?
A generator is a function that returns an object (iterator) which we can iterate over
(one value at a time).
Generators are used to create iterators, but with a different approach.
What is a generator?
A generator is a function that returns an object (iterator) which we can iterate over
(one value at a time).
Generators are used to create iterators, but with a different approach.
Generators are simple functions which return an iterable set of items, one at a
time, in a special way.
What is a generator?
A generator is a function that returns an object (iterator) which we can iterate over
(one value at a time).
Generators are used to create iterators, but with a different approach.
Generators are simple functions which return an iterable set of items, one at a
time, in a special way.
Generators are memory efficient.
Defining a generator
Defining a generator
def <generator>(<args>):
for <el> in <collection>:
yield <el>
Using a generator
Using a generator
<generator> = <generator>(<args>)
<el> = next(<generator>)
Using a generator in a list comprehension
Using a generator in a list comprehension
<list> = [<el> for <el> in <generator>(<args>)]
Classes
Class definition
Class definition
class <name>:
def __init__(self, a): # Constructor Overloading
self.a = a

def __repr__(self): # Return value of repr() should be unambiguous and of str() readable.
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'

def __str__(self): # If only repr() is defined, it will also be used for str().
return str(self.a)

@classmethod # Class methods can be called without an instance of the class.


def get_class_name(cls):
return cls.__name__

@staticmethod # Static methods can be called without an instance of the class.


def static_method(name):
return 'static_method by ' + name
Inheritance
Inheritance
class Person:
__slots__ = ['age', 'name']
# Mechanism that restricts objects to attributes listed in 'slots'
# and significantly reduces their memory footprint.
def __init__(self, name, age):
[Link] = name
[Link] = age

class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
Multiple inheritance
Multiple inheritance
class A: pass
class B: pass
class C(A, B): pass

# Method Resolution Order (MRO) determines the order in which parent classes
# are traversed when searching for a method or an attribute:
# >>> [Link]()
# [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
Property
Property
# Pythonic way of implementing getters and setters.
class Person:
@property
def name(self):
return ' '.join(self._name)

@[Link]
def name(self, value):
self._name = [Link]()

>>> person = Person()


>>> [Link] = '\t Guido van Rossum \n'
>>> [Link]
'Guido van Rossum'
Dataclass
Dataclass
# Dataclasses are a convenient way of defining classes that are mostly used to store data.
# They are a shorthand for defining classes
# with __init__(), __repr__(), __eq__() and other methods.

from dataclasses import dataclass

# order=False: disable ordering methods, frozen=False: disable immutability.


# For object to be hashable, all attributes must be hashable and 'frozen' must be True.

@dataclass(order=False, frozen=False)
class Person:
name: str
age: int
<attr_name_1>: <type>
# For attributes of arbitrary type use '[Link]'.
<attr_name_2>: <type> = <default_value>
<attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
# Function field() is needed because '<attr_name>: list = []'
# would make a list that is shared among all instances.
Dataclass Usage
Dataclass Usage
>>> person = Person('Guido', 64)
>>> person
Person(name='Guido', age=64)
>>> [Link]
'Guido'
>>> [Link]
64
Imports
Importing modules/packages
Importing modules/packages
# Imports a built-in or '<module>.py'.
import <module>
# Imports a built-in or '<package>/__init__.py'.
import <package>
# Imports a built-in or '<package>/<module>.py'.
import <package>.<module>

# Package is a collection of modules.


# On a filesystem this corresponds to a directory of Python files with an optional init script.
# Running 'import <package>' does not automatically provide access to the package's modules
# unless they are explicitly imported in its init script.
Exceptions
Exception handling
Exception handling
try:
<code>
# All variables that are initialized in executed blocks are also visible in all subsequent
# as well as outside the try/except clause (only function blocks delimit scope).
except <exception>:
<code>
# Use 'traceback.print_exc()' to print the error message to stderr.
except <exception> as <name>:
<code>
# Use 'print(<name>)' to print just the cause of the exception (its arguments).
except (<exception_1>, <exception_2>, ...):
<code>
except:
<code>
# Use '[Link](<message>)' to log the passed message,
# followed by the full error message of the caught exception.
else:
<code> # Executed if no exception was raised.
finally:
<code> # Executed regardless of whether an exception was raised.
Built-in Exceptions
Built-in Exceptions
BaseException
├── SystemExit # Raised by the [Link]() function.
├── KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
└── Exception # User-defined exceptions should be derived from this class.
├── ArithmeticError # Base class for arithmetic errors.
│ └── ZeroDivisionError # Raised when dividing by zero.
├── AssertionError # Raised by `assert <exp>` if expression returns false value.
├── AttributeError # Raised when object doesn't have requested attribute/method.
├── EOFError # Raised by input() when it hits an end-of-file condition.
├── LookupError # Base class for errors when a collection can't find an item.
│ ├── IndexError # Raised when a sequence index is out of range.
│ └── KeyError # Raised when a dictionary key or set element is missing.
├── MemoryError # Out of memory. Could be too late to start deleting vars.
├── NameError # Raised when nonexistent name (variable/func/class) is used.
│ └── UnboundLocalError # Raised when local name is used before it's being defined.
├── OSError # Errors such as FileExistsError/PermissionError (see Open).
├── RuntimeError # Raised by errors that don't fall into other categories.
│ └── RecursionError # Raised when the maximum recursion depth is exceeded.
├── StopIteration # Raised by next() when run on an empty iterator.
├── TypeError # Raised when an argument is of the wrong type.
└── ValueError # When argument has the right type but inappropriate value.
└── UnicodeError # Raised when encoding/decoding strings to/from bytes fails.
Useful build-in Exceptions
Useful build-in Exceptions
raise TypeError('Argument is of the wrong type!')
raise ValueError('Argument has the right type but an inappropriate value!')
raise RuntimeError('None of above!')
User-defined Exceptions
User-defined Exceptions
class MyError(Exception): pass
class MyInputError(MyError): pass
Open files
Opening files
Opening files
<file> = open(<path>, mode='r', encoding=None, newline=None)

# 'encoding=None' means that the default encoding is used, which is platform dependent.
# Best practice is to use 'encoding="utf-8"' whenever possible.
# 'newline=None' means all different end of line combinations are converted to '\n' on read,
# while on write all '\n' characters are converted to system's default line separator.
# 'newline=""' means no conversions take place, but input is still broken into chunks by
# readline() and readlines() on every '\n', '\r' and '\r\n'.
Modes of ppening files
Modes of ppening files
Read Text from File
Read Text from File
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return [Link]()
Write Text to File
Write Text to File
def write_to_file(filename, text):
with open(filename, 'w', encoding='utf-8') as file:
[Link](text)
Paths
Define a Path
Define a Path
from pathlib import Path

<Path> = Path(<path> [, ...]) # Accepts strings, Paths and DirEntry objects.


<Path> = <path> / <path> [/ ...] # First or second path must be a Path object.
Get current path
Get current path
<Path> = Path() # Returns relative cwd. Also Path('.').
<Path> = [Link]() # Returns absolute cwd. Also Path().resolve().
<Path> = [Link]() # Returns user's home directory (absolute).
<Path> = Path(__file__).resolve() # Returns absolute path of the current file.
Parts of the Path object
Parts of the Path object
<Path> = <Path>.parent # Returns Path without the final component.
<str> = <Path>.name # Returns final component as a string.
<str> = <Path>.stem # Returns final component without extension.
<str> = <Path>.suffix # Returns final component's extension.
<tup.> = <Path>.parts # Returns all components as strings.
Search a directory
Search a directory
<iter> = <Path>.iterdir() # Returns directory contents as Path objects.
<iter> = <Path>.glob('<pattern>') # Returns Paths matching the wildcard pattern.
Path manipulations
Path manipulations
<Path> = <Path>.with_name(<name>) # Returns Path with the final component replaced.
<Path> = <Path>.with_suffix(<ext>) # Returns Path with the final component's extension replaced
<Path> = <Path>.joinpath(<path>) # Returns Path with the given path appended.
<Path> = <Path>.expanduser() # Returns Path with the user's home directory expanded.
Path manipulations
Path manipulations
<Path> = <Path>.relative_to(<path>) # Returns Path relative to the given path.
<Path> = <Path>.absolute() # Returns absolute Path.
<Path> = <Path>.resolve() # Returns absolute Path.
<Path> = <Path>.as_posix() # Returns Path as a string using '/' as separator.
<Path> = <Path>.as_uri() # Returns Path as a string using '[Link] as prefix.
OS Commands
Manipulate OS files/directories
Manipulate OS files/directories
import os, shutil, subprocess

# Paths can be either strings, Paths or DirEntry objects.

[Link](<path>) # Changes the current working directory.


[Link](<path>, mode=0o777) # Creates a directory. Permissions are in octal.
[Link](<path>, mode=0o777) # Creates all path's dirs. Also: `exist_ok=False`.

[Link](from, to) # Copies the file. 'to' can exist or be a dir.


[Link](from, to) # Copies the directory. 'to' must not exist.

[Link](from, to) # Renames/moves the file or directory.


[Link](from, to) # Same, but overwrites 'to' if it exists.

[Link](<path>) # Deletes the file.


[Link](<path>) # Deletes the empty directory.
[Link](<path>) # Deletes the directory.
JSON
Convert from and into JSON
Convert from and into JSON
import json
<str> = [Link](<object>) # Converts object to JSON string.
<object> = [Link](<str>) # Converts JSON string to object.
Read JSON from file
Read JSON from file
import json

with open(<path>, 'r', encoding='utf-8') as file:


<dict> = [Link](file)
Write JSON to file
Write JSON to file
import json

with open(<path>, 'w', encoding='utf-8') as file:


[Link](<dict>, file, indent=2)
CSV
Read CSV
Read CSV
import csv

def read_csv_file(filename, dialect='excel'):


with open(filename, encoding='utf-8', newline='') as file:
return list([Link](file, dialect))

# File must be opened with a 'newline=""' argument,


# or newlines embedded inside quoted fields will not be interpreted correctly!
# To print the spreadsheet to the console use Tabulate library.
# For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
# Reader accepts any iterator of strings, not just files.
Write CSV
Write CSV
import csv

def write_to_csv_file(filename, rows, dialect='excel'):


with open(filename, 'w', encoding='utf-8', newline='') as file:
writer = [Link](file, dialect)
[Link](rows)

# ile must be opened with a 'newline=""' argument,


or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!
SQLite
Connect to database
Connect to database
import sqlite3

<connection> = [Link](<path>) # Opens existing or new file. Also ':memory:'.


<conn>.close() # Closes the connection.
Execute SQL
Execute SQL
<cursor> = <connection>.execute(<sql>) # Can raise a subclass of [Link].
<cursor> = <connection>.executescript(<sql>) # <sql> is a string with multiple SQL statements.
Fetch results
Fetch results
<list> = <cursor>.fetchall() # Returns remaining rows. Also list(<cursor>).
<tuple> = <cursor>.fetchone() # Returns next row. Also next(<cursor>).
Commit changes
Commit changes
<connection>.commit() # Commits changes to the database.
<conn>.rollback() # Discards all changes since the last commit.

# Or:
with <conn>: # Exits the block with commit() or rollback(),
<conn>.execute('<query>') # depending on whether any exception occurred.
Placeholders
Placeholders
<conn>.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
<conn>.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
<conn>.executemany('<query>', <coll_of_above>) # Runs execute() multiple times.
Cursor
Cursor
<cursor>.rowcount # Number of rows affected by the last query.
<cursor>.lastrowid # Row ID of the last row inserted.
<cursor>.description # Tuple of 7-tuples with column info.
<cursor>.connection # Connection object.
<cursor>.arraysize # Number of rows to fetch at a time.
<cursor>.setinputsizes(<list>) # Sets the input sizes for the given columns.
<cursor>.setoutputsize(<size>, <column>) # Sets the output size for the given column.
Example
Example
>>> conn = [Link]('[Link]')
>>> [Link]('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
>>> [Link]('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
1
>>> [Link]('SELECT * FROM person').fetchall()
[(1, 'Jean-Luc', 187)]

You might also like