Opening a file with python

This short article show you how to open a file using python. We will use the with keyword in order to avoid having to close the file.

There is no need to import anything in order to open a file. All the function related to file manipulation are part of the python standard library

In order to open a file, we will use the function open. This function takes two arguments :

  • the path of the file
  • the mode you want to open the file

The mode can be :

  • 'r' : read
  • 'w' : write
  • 'a' : append (writes at the end of the file)
  • 'b' : binary mode
  • 'x' : exclusive creation
  • 't' : text mode (by default)

Note that if the file does not exit it will be created if you use the following options "w", "a", "x". If you try to open a non existing file in read mode 'r', a FileNotFoundError will be returned.

It is possible to combine multiple options together. For instance, you can open a file in binary mode for writing using the 'wb' option.

Python distinguishes between binary and text I/O. Files opened in binary mode return contents as bytes objects without any decoding. In text mode , the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

Writing to a file

Let's first open (create) a text file a write a string to it.

filepath = ".\\myfile.txt"

with open(filepath, 'w') as f:
    f.write("Hello world !")

Reading a file

we can now see how to read the content of a file. To do so, we will use the 'r' option

with open(filepath, "r") as f:
    content  = f.read()

print(content)
Hello world !

A word on the with keyword

In python the with keyword is used when working with unmanaged resources (like file streams).

The python documentation tells us that :

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
        with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods).