Python – Getting Started with the Standard Library

File Wildcards

The glob module allows for making file lists from a directory

import glob

glob.glob("*.py")

This code will return all of the .py files in a directory as a list

Error output and application termination

The sys module contains system specific parameters and functions.

The easiest way to terminate a program is by using sys.exit()

You may also output an error using sys.stderr() which is used for error and warning messages.

String Pattern Matching

Use the re module provides regular expression tools for string pattern matching.

import re

re.findall(r'\bz[a-z]*', 'zebras are nice')

This code will find and return ‘zebras’ in the string.

Additionally use this code below for replacing words in a string:

'thinking is foolish'.replace('foolish', 'fun')

This code will replace fun with foolish

Access Internet

There are alot of modules to process internet protocols and access the internet. The simplest being urllib.request to retrieve data from a url.

from urllib.request import urlopenfrom urllib.request import urlopen
with urlopen('http://google.com') as response: 
  print(response.read().decode('utf-8'))

This code will print the source code behind the google webpage into your command prompt.

Dates and Times

The datetime module allows you to add and manipulate date values into your code.

from datetime import date

#print today's date
now = date.today()
print(now)

#print additional detail about today's date
newNow = now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
print(newNow)

Data Compression

zlib allows you to compress file size

import zlib

#create sample text variable
s = b'this is an example of how compression decreases the size of the file' 
#assess length of string
print(len(s))
#compress string
t = zlib.compress(s)
#see that length has been compressed
print(len(t))

**This article is written for Python 3.6

<< Classes

%d bloggers like this: