„Batteries included“¶
In Python, a library can consist of several components, including built-in data types and constants that can be used without an import statement, such as Numbers and Lists, as well as some built-in Functions and Exceptions. The largest part of the library is an extensive collection of Modules. If you have Python installed, there are also several libraries available for you to use.
Managing data types¶
The standard library naturally contains support for the types built into Python. In addition, there are three categories in the standard library that deal with different data types: Modules for strings, datatypes and numbers.
String modules¶
:
Module |
Description |
|---|---|
compares with constants such as |
|
searches and replaces text with regular expressions |
|
interprets bytes as packed binary data |
|
helps to calculate deltas, find differences between strings or sequences and create patches and diff files |
|
wraps and fills text, formats text with line breaks or spaces |
Checks¶
For example, can you add or multiply a string with an integer, a floating point number or a complex number?
How can you change a heading such as
variables and expressionsso that it contains hyphens instead of spaces and can therefore be better used as a file name?Which of the following strings cannot be converted into numbers and why?
int("1e2")
int(1e+2)
int("1+2")
int("+2")
If you want to check whether a line begins with
.. note::, which method would you use? Are there any other options?Suppose you have a string with exclamation marks, quotation marks and line breaks. How can these be removed from the string?
How can you change all spaces and punctuation marks from a string to a hyphen (
-)?What use cases can you imagine in which the
structmodule would be useful for reading or writing binary data?when reading and writing a binary file
when reading from an external interface, where the data should be stored exactly as it was transmitted
Which regular expression would you use to find strings that represent the numbers between -3 and +3?
Which regular expression would you use to find hexadecimal values?
Modules for data types¶
Module |
Description |
|---|---|
Time and calendar operations |
|
Container data types |
|
allows the creation of enumeration classes that bind symbolic names to constant values |
|
Efficient arrays of numeric values |
|
Event scheduler |
|
Synchronised queue class |
|
Shallow and deep copy operations |
|
prints Python data structures „pretty“. |
|
supports commenting code with hints about the types of objects, especially function parameters and return values |
Modules for numbers¶
:
Module |
Description |
|---|---|
for numeric abstract base classes |
|
for mathematical functions for real and complex numbers |
|
for decimal fixed-point and floating-point arithmetic |
|
for functions for calculating mathematical statistics |
|
for rational numbers |
|
for generating pseudo-random numbers and selections and for shuffling sequences |
|
for functions that create iterators for efficient loops |
|
for higher-order functions and operations on callable objects |
|
for standard operators as functions |
Checks¶
Create some number variables (integers, floating point numbers and complex numbers). Experiment a little with what happens when you perform operations with them, even across types.
Load the
mathmodule and try out some of the functions. Then load thecmathmodule and do the same.How can you restore the functions of the
mathmodule?Decide whether the following statements are true or false:
10-1[0]1 and 01 > 0 or []
Changing files¶
:
Module |
Description |
|---|---|
performs common pathname manipulations |
|
manipulates pathnames |
|
iterates over multiple input files |
|
compares files and directories |
|
creates temporary files and directories |
|
use UNIX-like path and file name patterns |
|
randomly accesses lines of text |
|
performs higher level file operations |
|
Assignment of file names to MIME types |
|
enable Python object serialisation and persistence, see also The pickle module |
|
reads and writes CSV files |
|
JSON encoder and decoder |
|
provides a DB-API 2.0 interface for SQLite databases, see also The sqlite module |
|
|
reads and writes XML files, see also R:doc:../save-data/xml |
Parsing HTML and XHTML |
|
reads and writes Windows-like configuration files ( |
|
encodes/decodes files or streams |
|
reads and writes structured data to and from files |
|
for working with archive files and compressions |
Checks¶
Uses the functions of the
osmodule to take a path to a file namedexample.logand create a new file path in the same directory for a file namedexample.log1.>>> import os >>> path = os.path.abspath("example.log") >>> print(path) /Users/veit/python-basics-tutorial-de/example.log >>> new_path = f"{path}2" >>> print(new_path) /Users/veit/python-basics-tutorial-de/example.log2
What is the significance of adding
bas a parameter toopen()?This opens the file in binary mode, which means that bytes and not characters are read and written.
Open a file
my_file.txtand insert additional text at the end of the file. Which command would you use to openmy_file.txt? Which command would you use to reopen the file and read it from the beginning?>>> with open("my_file", "a") as f: ... f.write("Hi, Pythinistas!\n") ... 17 >>> with open("my_file") as f: ... print(f.readlines()) ... ['Hi, Pythinistas!\n', 'Hi, Pythinistas!\n']
What use cases can you imagine in which the
structmodule would be useful for reading or writing binary data?Why pickle may or may not be suitable for the following use cases:
Saving some state variables from one run to the next
Storing evaluation results
Saving user names and passwords
Saving a large dictionary with English terms
If you look at the man page for the wc utility, you will see two command line options:
-ccounts the bytes in the file
-mcounts the characters, which in the case of some Unicode characters can be two or more bytes long
Also, if a file is specified, our module should read from and process that file, but if no file is specified, it should read from and process
stdin.If a context manager is used in a script that reads and/or writes multiple files, which of the following approaches do you think would be best?
Put the entire script in a block managed by a
withstatement.Use one
withstatement for all reads and another for all writes.Use a
withstatement every time you read or write a file, that is, for every line.Use a
withstatement for each file you read or write.
Archive
*.txtfiles from the current directory in thearchivedirectory as*.zipfiles with the current date as the file name.Which modules do you need for this?
Write a possible solution.
Interacting with the operating system¶
Module |
Description |
|---|---|
Various operating system interfaces |
|
Access to the identification data of the underlying platform |
|
Time access and conversions |
|
Tools for working with data streams |
|
Waiting for I/O completion |
|
Parser for command line options |
|
Terminal handling for character cell displays |
|
Portable password entry |
|
provides C-compatible data types |
|
high-level threading interface |
|
Process-based threading interface |
|
Management of subprocesses |
Use of Internet protocols¶
Module |
description |
|---|---|
Low-level network interface and SSL wrapper for socket objects |
|
Email and MIME processing package |
|
Manipulation of mailboxes in various formats |
|
|
Common Gateway Interface support |
WSGI utilities and reference implementation |
|
Open and parse URLs |
|
Clients for various Internet protocols |
|
Framework for network servers |
|
HTTP server |
|
XML-RPC client and server |
Developing and debugging¶
Module |
Description |
|---|---|
Documentation generator and online help system |
|
Test examples from Python docstrings |
|
Framework for unittests, see also Unittest |
|
Utility functions for tests |
|
traces the execution of Python statements |
|
Python debugger |
|
logging function for Python |
|
measures the execution time of small code snippets |
|
Python profiler |
|
System-specific parameters and functions |
|
Functions of the Python garbage collector |
|
inspects objects live |
|
exit handler |
|
Future statement definitions |
|
|
allows access to the import internals |
imports modules from zip archives |
|
finds modules used by a script |