A note to myself: permissions matter when writing to file

This is a bit elementary, but it's important to keep in mind how one is saving their data to file. Today's note is about the simplest form of file, the text (.txt) file. Note this also applies to the more space-efficient binary (.binary) file, which we can talk about later.

The standard matlab / python commands look like this:

fileID = fopen(filename, permission, machinefmt, encodingIn)

# Python
file_object = open(filename [, access_mode][, buffering])

If the file already exists, then opening the file is easy. You either get a fileID or file_object which points to that file.

But if you plan to interact with the file, the permission to that file needs to be specified. There are 3 common permissions you can specify for text files:

  1. 'r' - opens the file for reading only and points to the beginning of the file; the file being read must exist
  • Use this if you just need to read data from file
  1. 'w' - opens / creates a file for writing only; if the file already exists, all data in it is overwritten like a clean slate
  • Use this if you want to write to a clean file
  1. 'a' - opens / creates a file for writing only; unlike 'w', the file pointer is placed at the end of the file, meaning anything you write to it is added to the bottom of the file (append).
  • Use this if you want to keep adding information to a growing file

There are two additional toggles you can add to these file permissions:

  1. '+' - makes the file permission go both ways, so you can read and write
  • ex: 'w+' opens a file for both reading and writing
  1. 'b' - opens the file in binary format, which stores the data as 0's and 1's. This isn't so scary once you learn how different data types are encoded in binary (a topic for some other time).
  • ex: 'wb+' - opens a file for both reading and writing in binary format

What motivated me writing this in the first place was that I was trying to create a new file, but forgot to specify the permissions. Creating a new file with just the file name leads to an error, because you haven't provided enough information about what type of file you want to create. Mainly, you need to specify where the file pointer goes, and how are you planning to interact with said file.

In depth information for these MATLAB and Python function calls can be found on the links provided. Remember, the internet is a powerful ally for programmers.


Paolo Gabriel is a graduate student at University of California, San Diego. He is obtaining his PhD by conducting research with the Translational Neuroengineering Lab.