Basic File Handling and Parsing in Python

Joseph Mellor
9 min readFeb 23, 2023

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…

--

--

Joseph Mellor

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