Python is one of the most approachable languages to learn, thanks to its object-oriented-first approach and its minimal syntax. The standard library includes many useful modules that you can use to write all sorts of programs, big and small.

1 Batch File Renamer

Renaming a set of files can be a challenging task. If you can remember your shell syntax, you can write a command on the fly, or you can rely on a third-party program like rename.

This simple Python program renames all files in your current directory that contain specific text, replacing that text with a given pattern. You could use it, for example, to change a set of extensions from ".htm" to ".html."

        import os, sys

if len(sys.argv) < 3:
    sys.exit("usage: " + sys.argv[0] + " search replace")

for filename in os.listdir("."):
    new_filename = filename.replace(sys.argv[1], sys.argv[2])

    if new_filename != filename:
        os.rename(
            os.path.join(".", filename),
            os.path.join(".", new_filename),
        )

The script imports a couple of useful low-level modules: os and sys. It immediately uses the latter to check the number of arguments (sys.argv) and exits if too few are given.

The main for loop then iterates through all filenames in the current directory (.). The replace method of the string class then attempts to overwrite the first argument with the second.

A final check to see if the filename has changed is then followed by a call to os.rename() which updates the file if necessary.

This script lacks comprehensive error handling, and you should limit your use of it to simple string search and replace. Always be careful with batch operations that may affect many files.

2 Image Thumbnail Maker

The following four-line script shows the power of a convenient library, in this case, Pillow. This fork of the Python Imaging Library has many image-processing functions, to support anything from simple scripts to full-blown graphics editors.

You’ll need to install the Pillow library before you can run this script. brew install pillow worked well for me on macOS, but you can also try pip which the installation page recommends.

The script uses three methods from the Image module to open a file, create a thumbnail, and save it to a second file:

        from PIL import Image
image = Image.open("image.jpg")
image.thumbnail((500, 500))
image.save("image_thumb.jpg")

Note how the thumbnail function takes a single argument, which is a tuple. It will create an image with the same ratio as the original, with a maximum width and height according to the dimensions you provide.

On its own, this is of limited use since the filename and dimensions are hardcoded. You can extend its functionality by passing these values as command-line arguments instead, using a second version of the script which is not much bigger:

        from PIL import Image
import sys

if len(sys.argv) < 4:
    sys.exit("usage: " + sys.argv[0] + " image width height")

image = Image.open(sys.argv[1])
image.thumbnail((int(sys.argv[2]), int(sys.argv[3])))
image.save("thumb.jpg")

Note that the final thumbnail filename is still hardcoded. As a further extension, you could generate a filename based on the original, or accept a fourth command-line parameter.

3 Simple Web Server

A basic web server can be very useful; I use one to quickly browse and access files on my local computer. It can also be a handy tool for web development.

Few web servers are as simple as this:

        import http.server, socketserver

port = 8001

with socketserver.TCPServer(
    ("", port), http.server.SimpleHTTPRequestHandler
) as httpd:
    print(f"Serving at port {port}")
    httpd.serve_forever()

The http.server and socketserver modules do most of the work here. A generic TCPServer instance is passed a port and a SimpleHTTPRequestHandler which servers files from the current directory over HTTP. The serve_forever method (which is inherited from a socketserver.BaseServer class) handles requests until the shutdown() method is called.

As Python’s documentation warns, the http.server module lacks proper security and is not for production use.

Although this is just a toy server, it’s great for personal use and its simplicity is unrivaled.

4 Random Password Generator

Whether for a new user account, a web form, or your own development work, a random password is often called for. You should probably use a password manager to do this, but that’s not always appropriate. With your own script, you can control the exact details and refine it to suit your needs.

        import string, random

def main(length: int) -> str:
    characters = string.ascii_letters + string.digits + string.punctuation
    return "".join(random.choice(characters) for i in range(length))

print(main(32))

This script uses the string and random modules to generate a random password in just five lines of code. The string module has some helpful constants containing sets of individual characters like digits and letters. By combining these and picking a number at random, the script concatenates a series of characters to produce the final password.

Output from a password.py script run three times, each time showing a random series of characters including letters, digits, and punctuation.

5 Crypto Price Checker

This script demonstrates the power of a clean, simple API. The API it uses—from coingecko—runs over HTTP, so it’s very portable and easy to support.

Before you run this script, check out the API response from the endpoint it uses, /simple/price. You should see that it returns JSON-formatted data with entries for the currencies passed in the ids parameter.

        import urllib.request, json

def get_crypto_prices():
    url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,litecoin&vs_currencies=usd"
    ufile = urllib.request.urlopen(url)
    text = ufile.read()
    return json.loads(text)

crypto_prices = get_crypto_prices()

for coin, value in crypto_prices.items():
    print(f"{coin.capitalize()}: ${value['usd']}")

The urllib.request module includes a urlopen() method which fetches the contents of a URL and returns an HTTPResponse object. Reading its text and passing it to the json.loads() method constructs an equivalent dictionary object.

Output from a python script showing the current price of three cryptocurrencies: Bitcoin, Ethereum, and Litecoin.

JSON is a very popular format for web APIs because its simple syntax and human-readable format make it easy to parse and test.

6 ASCII Table Generator

The ASCII character set is a collection of 128 common characters from the English language, used in various computing contexts. Most programming languages support conversion of ASCII codes to individual characters, and vice versa, but it’s sometimes useful to see all ASCII characters at once.

        for i in range(32, 128):
    print("{:03d}".format(i) + " " + chr(i), end=" ")

    if (i - 1) % 10 == 0:
        print()

print()

This script prints a table containing all ASCII characters from 32 to 127, each alongside its code point:

The output from a python script showing an ASCII table, with codepoints from 32 to 127 and the corresponding character alongside.

The first thing to note is how the built-in Python function range() treats its parameters; it iterates starting from the first, but stops before it reaches the second. In a language like JavaScript, the equivalent for loop would look like this:

        for (i = 0; i < 128; i++) { ... }

Most of the remaining work is in the print() line and includes formatting each code point as a fixed width of three places. The chr() function returns a character given its ASCII code.

One useful property of ASCII, that this table demonstrates, is that the code of each lowercase letter (a-z) is exactly 32 greater than its uppercase equivalent.

The remaining trick is to print a newline character at the appropriate point, so the output is nicely split into rows. This uses the % operator to check the remainder of the range index when divided by 10, ensuring ten characters per line.

Related
How to Make Beautiful ASCII Art With These Cool Tools

Into the wonderful little world of the oldest digital art format.