Mihai Domocos
Brașov Get in touch
Chapter 7

File Input and Output

Files are a common way to store data in computer systems, and Python provides a powerful set of tools for working with files. We’ll learn how to read from and write to files, handle errors and exceptions, and work with different file formats. Whether you’re working with text files, binary files, or CSV files, this chapter will give you the skills you need to manipulate them in Python.

Reading and Writing to Files

Python allows us to read and write data to and from files. Reading data from a file is a way to extract data from an external source, while writing data to a file is a way to save data for later use. In Python, we can read and write files using built-in functions like open(), close(), read(), readline(), and write(). Example:

python
1# writing data to a file
2with open('my_file.txt', 'w') as file:
3 file.write('Hello, World!')
4
5# reading data from a file
6with open('my_file.txt', 'r') as file:
7 data = file.read()
8 print(data)

Context Managers

A context manager is a Python object that provides a way to manage resources such as files, sockets, and locks. The main advantage of using a context manager is that it automatically takes care of releasing the resources after use, even if an error occurs.

Example:

python
1# using a context manager to open a file
2with open('my_file.txt', 'r') as file:
3 data = file.read()
4 print(data)

File Modes

In Python, we can specify the mode in which we want to open a file using a second argument to the open() function. The available modes are:

  • 'r' : read-only mode
  • 'w' : write mode
  • 'a' : append mode
  • 'x' : exclusive creation mode

Example:

python
1# opening a file in write mode
2with open('my_file.txt', 'w') as file:
3 file.write('Hello, World!')

Handling Exceptions

When working with files, it is important to handle exceptions properly. Errors can occur if a file is not found, if there are permission issues, or if there are other problems with the file. In Python, we can use a try-except block to catch and handle exceptions that may occur.

Example:

python
1# handling exceptions when reading from a file
2try:
3 with open('my_file.txt', 'r') as file:
4 data = file.read()
5except FileNotFoundError:
6 print('File not found!')
7except PermissionError:
8 print('Permission denied!')
9except Exception as e:
10 print(f'Error: {e}')

This site remembers your theme choice and, with your consent, uses cookies for analytics. Cookie policy