Libraries

import modulname                        # = Dateiname
z = Modulname.Funktionsname()           # Aufruf mit Modulname
from modulname import funktionsname
from modulname import *                 # alle Funktionen importieren
z = Funktionsname()                     # Aufruf ohne Modulname

argparse

BeautifulSoup (*)

to be added

Build-in

datetime

from datetime import datetime, date, time
n = datetime.now()                              # Objekt mit aktuellem Datum + Uhrzeit, nur für datetime-Objekte
d = datetime(y, m, d, h, m, s)                  # erzeugt datetime-Objekt (analog auch date- oder time-Objekte)
jahr = d.year() / .month() / .day() / .minute() # Zugriff auf einzelne Teile des Objekts (analog auch date- oder time-Objekte)
if d == n: ...                                  # Vergleiche möglich (analog auch date- oder time-Objekte)
d.timestamp()                                   # Sekunden seit 01.01.1970, nur für datetime-Objekte
datetime.fromtimestamp(ts)                      # erzeugt datetime-Objekt aus timestamp (float)
c = datetime.combine(date-objekt, time-objekt)  # erzeugt datetime aus date und time
datetime.strftime(„%d-%m-%Y“)                   # Ausgabe „15-02-1988“, Format siehe Link
datetime.strptime(string, „%d.%m.%y“)           # datetime-Objekt aus String in vorgegebenem Format erstellen (z.B. aus CSV-Datei)

itertools

itertools.permutations(iterable)# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
itertools.count(start, step)    # count(2.5, 0.5) --> 2.5 3.0 3.5
itertools.cycle(iterbale)       # cycle('ABCD') --> A B C D A B C D A B C D
itertools.pairwise(iterable)    # pairwise('ABCDEFG') --> AB BC CD DE EF FG
itertools.product(*iterables)   # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy

JSON (*)

W3Schools

import json

with open(file_name, "r", encoding="UTF-8" as in_file:
    data = json.load(in_file)

# straight forward
key1 = data.get("key1", "")
if key1:
    pass

# nested structure
key3 = data.get("key1", {}).get("key2", {}).get("key3", "")

math

import math
math.sin(myfloat)
math.cos(myfloat)
math.pi                         # pi = 3.141592
math.e                          # e = 2.718281
math.tau                        # tau = 2*pi = 6.283185
math.ceil(x)                    # nächstgrößere int-Zahl
math.fabs(x)                    # absoluter Wert
math.floor(x)                   # nächstkleinere int-Zahl
m,e = math.frexp(x)             # Mantisse (float) und Exponent (int)
math.trunc(x)                   # foat => int
math.exp(x)                     # = e^x
math.log(x[, base])             # = ln(x)
math.log2(x)                    # Logarithmus zur Basis 2
math.log10(x)                   # = log(x)
math.pow(x, y)                  # = x^y
math.sqrt(x)                    # Wurzel
math.degrees(x)                 # rad => deg
math.radians(x)                 # deg => rad

matplotlib

see separate module

mmh3 (MurmurHash)

>>> import mmh3
>>> mmh3.hash("foo") # returns a 32-bit signed int
-156908512
>>> mmh3.hash("foo", 42) # uses 42 as a seed
-1322301282
>>> mmh3.hash("foo", signed=False) # returns a 32-bit unsigned int
4138058784

numpy

see separate module

os & os.path

import os
os.path.exists("input.txt")                             # Datei im gleichen Verzeichnis testen
os.path.exists("/input.txt")                            # Datei im Root-Verzeichnis testen
os.path.exists("docs")                                  # Ordner im gleichen Verzeichnis testen
os.path.exists("/docs")                                 # Ordner im Root-Verzeichnis testen
os.path.isfile(infile)
os.path.isdir(path)
os.path.getsize(path)

os.listdir("D:\\")                                      # Ordner & Files
os.scandir(path)                                        # Ordner & Files, Interator

os.path.joinjoin('usr', 'bin', 'spam')                  # => 'usr\\bin\\spam'
os.getcwd()                                             # Current Working Directory
os.chdir('C:\\Windows\\System32')
os.makedirs('C:\\delicious\\walnut\\waffles')
os.path.basename('C:\\Windows\\System32\\calc.exe')     # => 'calc.exe'
os.path.dirname('C:\\Windows\\System32\\calc.exe')      # => 'C:\\Windows\\System32'

os.path.dirname(__file__)                               # path to python file
os.path.join(os.path.dirname(__file__), „file.txt“)     # path to file.txt in same folder as python file
os.path.split('C:\\Windows\\System32\\calc.exe')        # => ('C:\\Windows\\System32', 'calc.exe')
os.path.splitdrive('C:\\Windows\\System32\\calc.exe')   # => ('C:', '\\Windows\\System32\\calc.exe')
os.path.splitext('C:\\Windows\\System32\\calc.exe')     # => ('C:\\Windows\\System32\\calc', '.exe')
os.path.splitunc(path)

os.getlogin()        # user name

PIL(*)

to be added

PyPDF2

import PyPDF2

with open(file_name, "rb") as file:
    reader = PyPDF2.PdfFileReader(file)  # `, strict=False`

    num_pages = reader.numPages
    page1 = reader.pages[0].extractText()

random

import random
random.seed()                   # Zufallsgenerator initialisieren
myint = random.randint(1,10)    # Zufallszahl zwischen 1 und 10
myfloat = random.random()       # zwischen 0 und 1
random.choice(seq)              # Return a random element from the non-empty sequence seq.
                                # If seq is empty, raises IndexError.
random.choices(pop, weights)    # choose one element from pop according to weighted propability
random.shuffle(list)            # in place
random.sample(popul, length)    # Return a k length list of unique elements chosen from the population sequence
random.uniform(a, b)            # floating point number a <= x <= b, even distribution
random.gauss(mu, sigma)         # floating point number, mu = mean, sigma = std-dev, normal distribution
random.sample(list, num)        # zieht zufällig eine Menge von num aus list

re

import re
pattern = r"\d\d:\d\d"
match = re.findall(pattern, "um 12:37 Uhr gibt es Mittagessen")

requests

import requests

x = requests.get('https://w3schools.com/python/demopage.htm')
print(x.text)

shutil

Dateioperationen wie z.B. kopieren oder verschieben

import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)  # dst can be a folder; use shutil.copy2() to preserve timestamp

sys

sys.argv[0]    # python script name
sys.argv[1:]   # parameters given to python script
sys.exit()     # stop program with error
sys.getwindowsversion()
sys.path       # system path?
sys.platform   # 'linux', 'win32', ...

textract

extract text from various different documents https://textract.readthedocs.io/en/stable/

tkinter

see separate module

webbrowser

import webbrowser

webbrowser.open('http://google.co.kr', new=2)  # 2 = new tab
webbrowser.open(f"https://www.startpage.com/sp/search?query={search}", new=2)
# use http/https to use firefox