Python Cookbook

Python
Cheat Sheet
Cookbook
Author

Louis Becker

Published

March 28, 2023

Purpose

This post serves as a quick-view cookbook and cheat sheet for myself to remember some basic commands and tips for python. Coming from an R background, I often forget the syntax needed for some basic operations. hey

Utilities

See libraries that can be updated

pip list --outdated

Update all python libraries

Windows

pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_}

Linux

pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U 

List files in a directory

import os

wd = os.getcwd()
os.listdir(wd)
['image.jpg', 'python_cookbook.ipynb', 'python_cookbook.qmd']

Data

Download a file from a web url

import os
import requests

url = 'http://api.kibot.com/?action=history&symbol=IVE&interval=tickbidask&bp=1&user=guest'

r = requests.get(url, stream=True)

with open("data.csv","wb") as pdf:
    for chunk in r.iter_content(chunk_size=1024):
  
         # writing one chunk at a time to pdf file
         if chunk:
             pdf.write(chunk)