Operations with files in Python

In this lesson we will study how to perform operations with files in Python.

In fact, in Python, as in other programming languages, you have functions for Input / Output operations on files, not unlike those for I / O on consoles.

We remind you that with the term file we mean everything that can be recorded on a mass storage medium (hard disk, pen drive, etc.).

The file is identified by a name and extension. The name is usually significant, in order to make us understand the content that the file contains. While the extension identifies the program with which it must be run.

The operations that are performed on the files are those of:

  • open – the file, saved in the mass memory, is loaded into the main memory usually for reading or writing operations.
  • close– the file loaded in the main memory is closed, that is, the connection between the main memory and the mass memory that contains that file is interrupted.
  • read – after the opening operation, the reading can be carried out. I.e. the contents of the file are interpreted by loading it into the main memory.
  • write – after the opening operation you can perform the write operations on the file, or you can save the changes in the main memory.

Reading is indicated with INPUT (from the mass memory to the central memory). While the writing is indicated with OUTPUT (from the central memory to the mass memory). Operations that are used to transfer information from main memory to mass storage are called Input / Output operations.

Operations with files in Python – file types

Files handled by the file system can be split into text files or binary files.

But what’s the difference and why do we need to know it?

These files encode the data differently:

  • Text files, also known as ASCII files, contain end-of-line (EOL) characters and each byte represents one character of the ASCII encoding. They are suitable for storing data of different lengths, they are heavier but can be read on computers that have different operating systems.
  • Binary files, on the other hand, are considered as a continuous stream of bits, are faster in reading and writing operations, and take up less disk space.

In Python we use text files to manage textual information while binary files to manage, for example, images or sounds. We keep this information in mind for the file operations in Python that we will see in the next lessons.

In this lesson we talked about file operations in Python, in the next lesson we will study many methods to operate on files.

Some useful links

Python tutorial

Python Compiler

Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python


No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *