Skip to content

Introduction

Python provides simple and powerful tools for working with files. Common operations include opening, reading, writing, and closing files, and are primarily performed using the open() and with functions.

open.py
open(file_route, mode)
  • file_route: the file’s location (relative or absolute).

  • mode: the operation mode

ModeDescription
r Opens the file in read mode. Raises an error if the file does not exist.
wOpens the file in write mode. Creates the file if it does not exist or overwrites it.
aOpens the file in append mode. Creates the file if it does not exist and writes at the end.
r+Opens the file in read and write mode. Does not truncate.
w+Opens the file in read and write mode, but overwrites the content.
a+Opens the file for reading and appending. The write pointer is at the end.
rbSame as 'r' but in binary mode.
wbSame as 'w' but in binary mode.
abSame as 'a' but in binary mode.
r+bReading and writing in binary mode.
w+bReading and writing, truncating the file, in binary mode.
a+bReading and appending in binary mode.

It is recommended to use open() together with the with statement, which ensures that the file is closed automatically at the end of the block, even if an error occurs:

with.py
with open('file.txt', 'r') as file:
    contenido = file.read()
  • with opens the file and assigns it to the variable file.

  • When exiting the with block, the file is closed automatically.