This article is a part of a 30 day Python challenge series. You can find the links to all the previous posts of this series here
- 30 Days of Python 👨💻 - Day One - Introduction
- 30 Days Of Python 👨💻 - Day 2 - Data Types I
- 30 Days of Python 👨💻 - Day 3 - Data Types II
- 30 Days Of Python 👨💻 - Day 4 - Data Types III
- 30 Days Of Python 👨💻 - Day 5 - Conditions And Loops I
- 30 Days Of Python 👨💻 - Day 6 - Loops II And Functions
- 30 Days Of Python 👨💻 - Day 7 - Developer Environment
- 30 Days Of Python 👨💻 - Day 8 - OOP Basics
- 30 Days Of Python 👨💻 - Day 9 - OOP Pillars
- 30 Days Of Python 👨💻 - Day 10 - OOP Missing Pieces
- 30 Days Of Python 👨💻 - Day 11 - Functional Programming
- 30 Days Of Python 👨💻 - Day 12 - Lambda Expression And Comprehensions
- 30 Days Of Python 👨💻 - Day 13 - Decorators
- 30 Days Of Python 👨💻 - Day 14 - Handling Errors
- 30 Days Of Python 👨💻 - Day 15 - Generators
- 30 Days Of Python 👨💻 - Day 16 - Module Basics
- 30 Days Of Python 👨💻 - Day 17 - External Modules
Today I explored how to handle files and communicate with files using Python. All these days, I have been exploring and sharing about various Python concepts along with some best practices to program in Python. However, we haven’t interacted with the outside world outside Python. Our programs often need to communicate with the external world for various reasons such as reading data from excel, CSV or pdf files, converting and compressing images, extracting data from text files, reading data from a database and countless other things. This interaction with the external world is done using I/O or input-output operations.
Files help us store data permanently into systems. When we write any program to manage some data, the data is stored temporarily in the RAM of the machine and gets erased when the computer is turned off. To store data permanently, they need to be stored in some kind of a database or in some file systems so that can be accessed for later use.
Files can be broadly classified based on their content into two types,
- Binary (Also called as Rich text)
- Text
If you are interested to know more about these two file types here is a great article to checkout.
Python provides a built-in function open to open any file. Any file first needs to be opened to read data from it or write some data onto it. Reading data from a file is simple in Python.
I used REPL as the playground to experiment with all the code-blocks provided in this article.
Opening Files
I created a test.txt file with some dummy content for testing.
test.txt
- # test.txt I am learning python.
Now the contents of this file can be read using Python like this.
main.py
- content = open('test.txt')
- output = content.read()
- print(output) # I am learning python.
We can also specify the mode while opening the file in the open function. By default, the mode is ‘r’ or read mode. We can also specify if the file needs to be opened in a text or binary mode.
| Mode | Description |
|---|---|
| r | Opens a file for reading. (default) |
| w | Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. |
| x | Opens a file for exclusive creation. If the file already exists, the operation fails. |
| a | Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. |
| t | Opens in text mode. (default) |
| b | Opens in binary mode. |
| + | Opens a file for updating (reading and writing) |
We can also specify the encoding format while opening a file. The default format is utf-8
Closing Files
It is important to close the file after performing operations on it as it will free up the memory space associated with the file.
main.py
- content = open('test.txt', mode='r')
- output = content.read()
- print(output)
- content.close()
The above block can be placed inside a try-except finally block. This ensures that if there is any error while performing the operation, the file will be closed.
main.py
- try:
- content = open('test.txt', mode='r')
- output = content.read()
- print(output)
- except FileNotFoundError as error:
- print(f'file not found {error}')
- finally:
- content.close()
Python provides a better syntax to open a perform operations on a file using the with statement. It automatically closes the file once the operation is performed.
main.py
- with open('test.txt', mode='r') as content:
- output = content.read()
- print(output) # I am learning python.
Writing to Files
Python provides write method to write data to a file. The file needs to be opened using w mode to write to a file. It is to be noted that using the w mode overrides the content of the file. If the content needs to be appended, then the a mode can be used. If the file does not exist, the file is created before writing data to it.
main.py

Join the conversation! Your thoughts help the community grow.