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()
Section titled “open()”open(file_route, mode)
-
file_route: the file’s location (relative or absolute).
-
mode: the operation mode
Opening modes
Section titled “Opening modes”Mode | Description |
---|---|
r | Opens the file in read mode. Raises an error if the file does not exist. |
w | Opens the file in write mode. Creates the file if it does not exist or overwrites it. |
a | Opens 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. |
rb | Same as 'r' but in binary mode. |
wb | Same as 'w' but in binary mode. |
ab | Same as 'a' but in binary mode. |
r+b | Reading and writing in binary mode. |
w+b | Reading and writing, truncating the file, in binary mode. |
a+b | Reading 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 open('file.txt', 'r') as file: contenido = file.read()
-
with
opens the file and assigns it to the variablefile
. -
When exiting the
with
block, the file is closed automatically.