Basic File Handling and Parsing in Python
--
Knowing how to properly read, write, and parse data is essential to doing anything useful with python.
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.
- Previous Article
- Next Article
- All Articles
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:
- The name of the file you want to open (either with a relative or an absolute path).
- 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…