Nearby lessons
87 of 159Python - File Handling
- 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.
- Text Files - used to store character data.
- 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
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()
Parameters
- filename - the name of the file.
- mode - specifies how the file should be opened.
Example
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.
- Read Mode (
r) - opens an existing file for reading. The file pointer is placed at the beginning. If the file does not exist, Python raisesFileNotFoundError. This is the default mode. - 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. - 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. - 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. - Write and Read Mode (
w+) - used for writing as well as reading. Existing data is overwritten. - Append and Read Mode (
a+) - used to append and read data. Existing data is not overwritten. - Exclusive Creation Mode (
x) - used to create a new file for writing. If the file already exists, Python raisesFileExistsError.
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.
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.
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.
Explanation
Let's understand the output of the above program:
f.namereturnsabc.txtbecause the file is opened with that name.f.modereturnswbecause the file is opened in write mode.f.readable()returnsFalsebecause write mode does not support reading.f.writable()returnsTruebecause write mode supports writing.f.closedreturnsFalsebeforeclose()is called andTrueafter 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. |
- 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