Useful Python
()
About this ebook
Python is a versatile and powerful language that can be used for a wide variety of tasks. In this book, we'll look at how Python can be used for various tasks that will make your life easier:
- Python as a “glue” language: it helps us combine skills and programs we already know how to use by allowing us to easily convert data from one format to another. This means that we can take data in one format that we don’t have tools to manipulate and change it into data for tools that we’re comfortable with. Whether we need to process a CSV, web page, or JSON file, Python can help us get the data into a format we can use.
- Python for stitching together other things. Sometimes we need to do more than process the data in an Excel file we’ve been sent. For example, we may want to fetch some pages from the Web, or work with an online API, or control our computer itself (such as renaming a batch of files, or changing how our operating system works). Python is great at these tasks.
- Words and numbers. Python is a powerful tool that can be used to solve a wide variety of problems, both big and small. In this tutorial, we’ll explore how to use Python to answer questions, solve puzzles, and simulate various scenarios.
- Running someone else’s Python code. Unlike many other languages, Python actually comes with modules for all sorts of useful functions. But for the times when we want to do things not covered by the standard library, we can use PyPI, a vast collection of open-source software libraries, frameworks and applications that can be easily installed and used in Python projects. We'll look at some examples.
We’re also going to assume a little knowledge of Python and programming already—such as what a variable is, what a dictionary is, and how to import a module.
Stuart Langridge
Stuart is a consultant CTO, software architect, and developer to startups and small firms on strategy, custom development, and how to best work with the dev team. Code and writings are to be found at kryogenix.org and social networks; Stuart himself is mostly to be found playing D&D or looking for the best vodka Collins in town.
Related to Useful Python
Related ebooks
Flask By Example: Unleash the full potential of the Flask web framework by creating simple yet powerful web applications Rating: 4 out of 5 stars4/5Profound Python Rating: 5 out of 5 stars5/5Modular Programming with Python Rating: 0 out of 5 stars0 ratingsBuilding RESTful Python Web Services Rating: 4 out of 5 stars4/5Data Structure in Python: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsMastering Objectoriented Python Rating: 5 out of 5 stars5/5Distributed Computing with Python Rating: 0 out of 5 stars0 ratingsPython 3 Object Oriented Programming Rating: 4 out of 5 stars4/5Python In - Depth: Use Python Programming Features, Techniques, and Modules to Solve Everyday Problems Rating: 0 out of 5 stars0 ratingsPython Web Scraping: Successfully scrape data from any website with the power of Python Rating: 4 out of 5 stars4/5Text Analytics with Python: A Brief Introduction to Text Analytics with Python Rating: 0 out of 5 stars0 ratingsPython Mastery: From Absolute Beginner to Pro Rating: 0 out of 5 stars0 ratingsPython Tools for Visual Studio Rating: 0 out of 5 stars0 ratingsNumPy Essentials Rating: 0 out of 5 stars0 ratingsBuilding the Future: Advanced Web Development Techniques with Flask and Python Rating: 0 out of 5 stars0 ratingsPython Parallel Programming Cookbook Rating: 5 out of 5 stars5/5Python Internals for Developers: Practice Python 3.x Fundamentals, Including Data Structures, Asymptotic Analysis, and Data Types Rating: 0 out of 5 stars0 ratingsPython Essentials Rating: 5 out of 5 stars5/5Advance Core Python Programming: Begin your Journey to Master the World of Python (English Edition) Rating: 4 out of 5 stars4/5Python 3 Object-oriented Programming - Second Edition Rating: 4 out of 5 stars4/5Learning Flask Framework: Build dynamic, data-driven websites and modern web applications with Flask Rating: 4 out of 5 stars4/5Python Web Scraping - Second Edition Rating: 5 out of 5 stars5/5Getting Started with Julia Rating: 0 out of 5 stars0 ratingsDaniel Arbuckle’s Mastering Python Rating: 0 out of 5 stars0 ratingsExploring the Python Library Ecosystem: A Comprehensive Guide Rating: 0 out of 5 stars0 ratings
Programming For You
iOS 26 App Development Essentials - SwiftUI Edition: Developing iOS 26 Apps using SwiftUI, Swift and Xcode 26 Rating: 0 out of 5 stars0 ratingsLearn SAP BI in 24 Hours Rating: 3 out of 5 stars3/5PHP, MySQL, & JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5PowerShell 7 for IT Professionals Rating: 1 out of 5 stars1/5Programming in Python: Learn the Powerful Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsProxmox Administration Essentials: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsSAP Service Management - Advanced Configuration Guide 2 Rating: 0 out of 5 stars0 ratingsThe Book of Powershell Rating: 0 out of 5 stars0 ratingsCreating ELearning Games with Unity Rating: 0 out of 5 stars0 ratingsLearning LEGO MINDSTORMS EV3 Rating: 5 out of 5 stars5/5PHP & MySQL Practice It Learn It Rating: 4 out of 5 stars4/5Swipe This!: The Guide to Great Touchscreen Game Design Rating: 4 out of 5 stars4/5JavaScript Made Easy: A Beginner's Practical Guide to Coding Interactive Web Pages Rating: 0 out of 5 stars0 ratingsUnity Multiplayer Games Rating: 5 out of 5 stars5/5Excel VBA Programming: Task Optimization and Daily Work Automation Rating: 0 out of 5 stars0 ratingsOntotext GraphDB in Practice: The Complete Guide for Developers and Engineers Rating: 0 out of 5 stars0 ratingsLearn to Code with Scratch: Let Your Kids' Creative Ideas Come to Life by Coding Them into Programs Rating: 0 out of 5 stars0 ratingsGood Luck Have Fun: The Rise of eSports Rating: 3 out of 5 stars3/5Beginning Programming with Java For Dummies Rating: 5 out of 5 stars5/5Python For Kids For Dummies Rating: 0 out of 5 stars0 ratingsMinecraft: 70 Top Minecraft Mods That Your Friends Do Not Know (But Wish They Did!) Rating: 4 out of 5 stars4/5Hacking Android Rating: 5 out of 5 stars5/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5
Reviews for Useful Python
0 ratings0 reviews
Book preview
Useful Python - Stuart Langridge
Chapter 1: Python as Glue
Python is a versatile and powerful language that can be used for a wide variety of tasks. One of the most common use cases for Python is as a glue
language: it helps us combine skills and programs we already know how to use by allowing us to easily convert data from one format to another. This means that we can take data in one format that we don’t have tools to manipulate and change it into data for tools that we’re comfortable with. Whether we need to process a CSV, web page, or JSON file, Python can help us get the data into a format we can use.
For example, we might use Python to pull data from a web page and put it into Excel, where we already know how to manipulate it. We might also read a CSV file downloaded from a website, calculate the totals from it, and then output the data in JSON format.
Who This Series is For
In this series of tutorials, we’re not looking at data science. That is, this isn’t about doing heavy statistical or numerical calculations on data we’ve received. Python is one of the industry-standard tools for doing calculations like these—using libraries such as NumPy and pandas—and there are plenty of resources available for learning data science (such as Become a Python Data Scientist).
In this series, we’ll looking at how to convert data from one form to another so that we can then go on to manipulate it.
We’re also going to assume a little knowledge of Python and programming already—such as what a variable is, what a dictionary is, and how to import a module. To start learning Python (or any other programming language) from scratch, check out SitePoint’s programming tutorials. The Python wiki also has a list of Python programming tutorials for programmers.
Getting Started
We’ll start this tutorial by looking at how to read data and then how to write it to a different format.
Reading Data
Let’s try an example. Let’s imagine we’re an author on a tour of local libraries, talking to people about our books. We’ve been given plymouth-libraries.json—a JSON file of all the public libraries in the town of Plymouth in the UK—and we want to explore this dataset a little and convert it into something we can read in Excel or Google Sheets, because we know about Excel.
First, let’s read the contents of the JSON file into a Python data structure:
import json
with open(plymouth-libraries.json
) as fp:
library_data = json.load(fp)
Now let’s explore this data a little in Python code to see what it contains:
print(library_data.keys())
This will print dict_keys(['type', 'name', 'crs', 'features']), which are the top-level keys from this file.
Similarly:
print(library_data[features
][0][properties
][LibraryName
])
This will print Central Library, which is the LibraryName value in properties for the first entry in the features list in the JSON file.
This is the most basic, and most common, use of Python’s built-in json module: to load some existing JSON data into a Python data structure (usually a Python dictionary, or nested set of Python dictionaries).
Bear in mind that, to keep these examples simple, this code contains no error checking. (Check out A Guide to Python Exception Handling for more on that.) But handling errors is important. For example, what would happen if the plymouth-libraries.json file didn’t exist? What we do in that situation depends on how we should react for errors. If we’re running this script by hand, Python will display the exception that occurs—in this case, a FileNotFoundError exception. Simply seeing that exception may be enough; we may not want to handle
this in code at all:
$ python load-json.py
Traceback (most recent call last):
File /home/aquarius/Scratch/fail.py
, line 13, in
open(plymouth-libraries.json
)
FileNotFoundError: [Errno 2] No such file or directory: 'plymouth-libraries.json'
If we’d like to do something more than have our program terminate with an error, we can use Python’s try and except keywords (as the exception handling article above describes) to do something else of our choosing. In this case, we display a more friendly error message and then exit (because the rest of the program won’t run without the list of libraries!):
try:
with open(plymouth-libraries.json
) as fp:
library_data = json.load(fp)
except FileNotFoundError:
print(I couldn't find the plymouth-libraries.json file!
)
sys.exit(1)
Writing
Now we want to write that data from its Python dictionary into a different format on disk, so we can open it in Excel. For now, let’s use CSV format, which is a very simple file format that Excel understands. (If you’re thinking, Hey, why don’t we make it a full Excel file!
… then read on. CSV is simpler, so we’ll do that first.) This process of taking Python data structures and writing them out as some file format is called serialization. So we’re going to serialize the data we read as JSON into CSV format.
The image below demonstrates the stages involved in serialization.
A one-row table laying out the serialization process: data, to lists and dicts, to data in Y format on discA CSV file is a text file of tabular data. Each row of the table is one line in the CSV file, with the entries in the row separated by commas. The first line of the
