File Handling
title: Python File Handling description: Python allows us to read, write, create and delete files. keywords: [Python File Handling, creating files in python, deleting files in python, modifying files in python, reading files in python] author: Juma Shafara date: "2023-11"

Python allows us to read, write, create and delete files. This process is called file handling. This is what we will discuss in this lesson
The open() function
The open() function allows us to read, create and update files
It takes 2 parameters:
file- the file or file path to be openedmode- the mode in which a file is opened for
The mode is a string that can either be any of the following:
| Mode | Meaning |
|---|---|
'r' | Open a file for reading |
'w' | Open a file for writing, creates the file if it does not exist |
'a' | Open a file for writing, appends to the end of the file |
'x' | Open a file for creating, fails if file already exists |
Python File reading
To better explain this, let us say we have a folder named my_folder.
Inside my_folder we have the following files:
demo.txtmain_code.py
The content of the demo.txt file is the following
demo.txt file and then print it using the main_code.py file To achieve this, we will use the open() function with 'r' mode.
Reading Lines
We can also read each line using the readline() method.
Writing a File
In simplest terms, writing a file means modifying the content of a file or creating it if it doesnot exist yet.
In Python, there are 2 modes to write to file.
'w'- overwrites content of a file, creates file if it does not exist'a'- appends content to the end of a file, creates the file if it does not exist
Example To better explain this, lets say we have a folder named my_folder. Inside my_folder we have the following files
demo.txtmain_code.py
The content of the demo.txt file is the following
'w' mode which will overwrite(replace) the content of the file Deleting a file
To delete a file, use the os module. The os modules contains the remove() method which we can use to delete files.
Exercise
- Develop a simple telephone directory which saves your friends contact information in a file named directory.txt. The program should have a menu similar to the following: When you press “1” it should request you to enter following data: After adding new contact information it should again display the menu. When you press “2” it should display all the contact information stored in the directory.txt file as follows: