Nearby lessons

87 of 159

Python - File Handling

📌 What You Will Learn
  • Understand why files are needed to store data permanently
  • Distinguish text files from binary files with real examples
  • Open a file using the open() function and understand its two parameters
  • Use the seven text file modes and their binary counterparts
  • Close a file and inspect the properties of a file object

Introduction to File Handling

As part of programming requirements, we have to store our data permanently for future use.

For this requirement, we should use files.

Files are very common permanent storage areas used to store data.

Why Do We Need File Handling?

Normally, the data stored in variables exists only while the program is running.

When the program terminates, that data is lost.

To store data permanently so that it can be used again in the future, Python provides File Handling.

Using files, we can save information permanently and access it whenever required.

Types of Files

There are two types of files.

  1. Text Files - used to store character data.
  2. Binary Files - used to store binary data such as images, videos, and audio.

Text Files

Usually, we use text files to store character data.

Examples include:

  • Notes
  • Logs
  • Source code
  • Configuration files
🐍Code Cell
1abc.txt
Output
No output captured.

Binary Files

Usually, we use binary files to store binary data such as:

  • Images
  • Video files
  • Audio files

Binary files store data in binary format instead of plain characters.

Comparison Between Text Files and Binary Files

Text Files Binary Files
Stores character data Stores binary data
Human readable Not directly human readable
Example: abc.txt Examples: Images, Videos, Audio files

Opening a File

Before performing any operation such as reading or writing, we must first open the file.

For this purpose, Python provides the built-in open() function.

At the time of opening the file, we must specify the mode, which represents the purpose of opening the file.

Syntax of open()

🐍Code Cell
1f = open(filename, mode)
Output
No output captured.

Parameters

  • filename - the name of the file.
  • mode - specifies how the file should be opened.

Example

🐍Code Cell
1f = open("abc.txt", "w")
Output
No output captured.

Explanation

The above statement opens the file abc.txt in write mode and stores the file object in the variable f.

File Modes in Python

Python supports the following file modes.

  1. Read Mode (r) - opens an existing file for reading. The file pointer is placed at the beginning. If the file does not exist, Python raises FileNotFoundError. This is the default mode.
  2. Write Mode (w) - opens a file for writing. If the file already contains data, the existing data is overwritten. If the file does not exist, a new file is created.
  3. Append Mode (a) - opens an existing file for appending data. Existing data is not overwritten; new data is added at the end. If the file does not exist, Python creates a new file.
  4. Read and Write Mode (r+) - used to both read and write data. Existing data is not deleted and the file pointer is positioned at the beginning.
  5. Write and Read Mode (w+) - used for writing as well as reading. Existing data is overwritten.
  6. Append and Read Mode (a+) - used to append and read data. Existing data is not overwritten.
  7. Exclusive Creation Mode (x) - used to create a new file for writing. If the file already exists, Python raises FileExistsError.

File Mode Summary

Mode Description
r Opens an existing file for reading (default mode).
w Opens a file for writing and overwrites existing data.
a Opens a file for appending data.
r+ Reads and writes without deleting existing data.
w+ Writes and reads; existing data is overwritten.
a+ Appends and reads without overwriting existing data.
x Creates a new file exclusively for writing.

Binary File Modes

All the above modes are applicable to text files.

If we suffix the mode with b, then it represents a binary file.

🐍Code Cell
1rb
2wb
3ab
4r+b
5w+b
6a+b
7xb
Output
No output captured.

Binary File Mode Summary

Mode Description
rb Read binary file.
wb Write binary file.
ab Append binary file.
r+b Read and write binary file.
w+b Write and read binary file.
a+b Append and read binary file.
xb Create a new binary file.

Closing a File

After completing all operations on a file, it is highly recommended to close the file.

For this purpose, we use the close() function.

Closing a file releases the resources associated with that file.

🐍Code Cell
1f.close()
Output
No output captured.

Various Properties of a File Object

Once a file is opened and we get a file object, we can access several properties related to that file.

Property / Method Description
name Returns the name of the opened file.
mode Returns the mode in which the file is opened.
closed Returns True if the file is closed; otherwise False.
readable() Returns True if the file is readable.
writable() Returns True if the file is writable.

Program: Display File Properties

The following program demonstrates how to access different properties of a file object.

🐍Code Cell
1f = open("abc.txt", "w")
2 
3print("File Name: ", f.name)
4print("File Mode: ", f.mode)
5print("Is File Readable: ", f.readable())
6print("Is File Writable: ", f.writable())
7print("Is File Closed : ", f.closed)
8 
9f.close()
10 
11print("Is File Closed : ", f.closed)
Output
File Name: abc.txt
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True

Explanation

Let's understand the output of the above program:

  • f.name returns abc.txt because the file is opened with that name.
  • f.mode returns w because the file is opened in write mode.
  • f.readable() returns False because write mode does not support reading.
  • f.writable() returns True because write mode supports writing.
  • f.closed returns False before close() is called and True after it.

Summary of File Object Properties

Property Returns
f.name Name of the file.
f.mode File opening mode.
f.closed True if closed; otherwise False.
f.readable() Whether the file can be read.
f.writable() Whether the file can be written.
📝 Key Takeaways
  • Files store data permanently; variables lose their data when the program ends
  • Text files store character data, while binary files store images, video, and audio
  • The open() function returns a file object, and the mode specifies how the file is opened
  • r is the default mode; w overwrites, a appends, and x raises FileExistsError
  • Suffixing any mode with b makes it work with binary files

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10