Basic File Handling and Parsing in Python

Joseph Mellor
9 min readFeb 23

Knowing how to properly read, write, and parse data is essential to doing anything useful with python.

Image made by me using the python logo, cool-retro-term, vim, the onedark color scheme, and GIMP.

By this point in the series, you should know how to write a program that gives a different output when given a different input. Now, we just need some way of giving the program various inputs.

While there are ways to give a program different inputs by typing things in the terminal, you’ll want most of the input to come from files. For this reason, let’s talk about how to interact with files in python. We’ll also talk about a few different ways to parse file input.

Topics Covered

As always, here are the topics covered. If you know these well, skip this article (and maybe read one of my other articles).

  • open: (file handling)
  • with: (automatic cleanup)
  • as: (renaming)
  • pass: (does nothing, no-op)
  • split: (string tokenization)
  • lambda: (lambda or anonymous functions)
  • sorted: (sorting)

I’m going to have to combine with and as since with generally needs an as and we won't cover the other big use of as in this article.

The open Statement

open, put simply, allows us to open files. It takes two arguments:

  1. The name of the file you want to open (either with a relative or an absolute path).
  2. The mode, or what you want to do with the file (read, write, append).

Relative and Absolute Paths

An absolute path is the easiest to explain, but it’s usually not used as often. Absolute paths use a universally defined location as its base. On Mac and Linux,/ or ~ are the most common ways to start an absolute path. On Windows, C:\ is the most common way.

A relative path uses the current location as a base. It uses ../ on Mac and Linux and..\ on Windows (but not the Windows Subsystem for Linux) to move up a directory. Other than that, they're the same. If you had a file…

Joseph Mellor

BS in Physics, Math, and CS with a minor in High-Performance Computing. You can find all my articles at