Python

String format

Positioning

'{1} {0}'.format('one', 'two')
# "two one"

Padding

'{:>10}'.format('abc')
# " abc"
'{:10}'.format('abc')
# "abc "
'{:^10}'.format('abc')
#
'{:_<10}'.format('abc')
# "abc_______"

Numbers

'{:06.2f}'.format(3.141592653589793)
# 003.14

Numbers format

Type Meaning
b Binary
c Unicode character
d Decimal
e Exponential notation (lowercase e)
E Exponential notation (uppercase E)
f Fixed point (lowercase inf and nan)
F Fixed point (uppercase INF and NAN)
g General (lowercase e)
G General (uppercase E)
n Same as d, but uses the number separator of locale settings
o Octal
x Hexadecimal (lowercase)
X Hexadecimal (uppercase)
% Percentage (multiply by 100 and puts % at the end)

Download files

Download a file as a string:

import urllib.request

def download_str(url):
with urllib.request.urlopen(url) as request:
return request.read()

Download a file:

import cgi
import posixpath
import urllib.parse
import urllib.request

def download_file(url, filename=None):
with urllib.request.urlopen(url) as request:
if filename is None:
header = request.headers.get("Content-Disposition", "")
_, params = cgi.parse_header(header)
filename = params.get("filename", "")
if not filename:
urlpath = urllib.parse.urlparse(url).path
filename = posixpath.basename(urlpath)
with open(filename, "wb") as file:
content = request.read()
file.write(content)

Fix error: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate>:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

csv

Read a CSV file.

data = []
with open(filename, "r") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
data.append(dict(zip(header, row)))
with open(filename, "r") as f:
reader = csv.DictReader(f)
data = [row for row in reader]

Write a CSV file.

with open(filename, "w") as f:
header = ["first_col", "last_col"]
writer = csv.DictWriter(f, header)
writer.writeheader()
for row in data:
writer.writerow(row)

virtualenv

Create a new environment (example: env):

virtualenv env

Or isolate the environment from the main package directory:

virtualenv --no-site-packages env

Now a folder (in this example, env) has been created. This folder should contain subfolders bin, include, lib. To enter the virtual environment:

source env/bin/activate
# pip install ...

You can use pip to install packages locally. In order to save the list of packages and their versions, you can use:

pip freeze > requirements.txt

In a new environment, to install packages and the versions listed in requirements.txt:

pip install -r requirements.txt

To exit the virtual environment:

deactivate