Programming and Computational Thinking

How do you work with files in Python

How do you work with files in Python

This post tells about how to work with files in Python. Writing your own programs, it is important to use files, that are stored at the secondary memory and can be accessed any time.

Before we are working with a file – writing or reading it – it must be opened. In order to open a file the program must communicate with operating system. Opening the file we ask operating system to find the file by name. If it is not found, we will get the error message.

If file is successfully opened we will get a file handle¬†<_io.TextIOWrapper  name=filename.txt  mode=r  encoding=cp1252>.

In our case text file consist of lines. This important point that will help us to understand what we can do with files.

Let’s see what we can do with files. We can:

  1. count the amount of lines in the file. In order to count the amount of lines Python separates lines using a new line character \n
  2. count amount of symbols in the file (including a new line characters)
  3. search through the file using string methods
  4. write the file

As the file was opened and all necessary actions are done, file should be closed with the corresponding closing method.

The examples of all these actions above we can do with files can be found in our Github library.

Educational content can also be reached via Reddit community r/ElectronicsEasy.