Simon Ward-Jones - Introducing More of the Standard Library | PyData London 2022 - 2022

Details

Title : Simon Ward-Jones - Introducing More of the Standard Library | PyData London 2022 Author(s): PyData Link(s) : https://www.youtube.com/watch?v=ypApmOoCRSc

Rough Notes

Using the Python standard library saves time, makes it easier for collaboration, means you don't reinvent the wheel, etc.

Python comes with more than 200 modules, some of the speakers favourites include os, sys, glob, re, math, random, statistics, urrlib.requests, datetime, string, collections, functools, unittest, itertools, email, threading, pathlib, json, logging, array, heapq, time.

This talk covers:

  • pathlib: classes representing filesystem paths.
  • datetime: classes for manipulating dates and times.
  • collections: specialized container datatypes.
  • itertools: fast, memory efficient tools for iteration.
  • functools: tools for higher order functions.

pathlib

from pathlib import Path

# Create path object at current path
cwd_path = Path('.')

# Variables containing current path, 2 ways
cwd_path.absolute()
Path.cwd()

# Building paths, 3 ways
student_folder = cwd_path.joinpath('data').joinpath('student-data')
student_folder = cwd_path / 'data' / 'student-data'
student_folder = Path('./data/student-data')

# Link to some actual file
student_data_path = student_folder / 'data.json'

# Attributes of the paths
student_data_path.name, student_data_path.stem, student_data_path.suffix

# Can call parents recursively
student_data_path.parent.parent

# Change suffix and names within the Python instance
student_data_path.with_suffix('.py')
student_data_path.with_name('student_data.txt')

# Interacting with files
student_data_path.exists()
student_data_path.is_file()
student_data_path.is_dir()

# To create a folder, alongside any parent folders if necessary,
# and no error if it already exists
student_data_folder.mkdir(parents=True, exists_ok=True)

# Write to actual file, assuming some json data in variable student_data
import json
student_data_path.write_text(json.dump(student_data, indent=4))

# Rename a file

Emacs 29.4 (Org mode 9.6.15)