FILE HANDLING IN PYTHON
1. Introduction
A file is a collection of data stored permanently on a storage device such as a hard disk.
Unlike variables, data in files does not disappear after the program ends.
2. What is File Handling?
File Handling means performing operations on files such as:
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
It helps in storing data permanently.
3. Real-Time Usage
File handling is used in:
• Saving user login data
• Storing logs in applications
• Data Science (CSV files)
• Banking systems
• Web applications
4. Types of Files
4.1 Text Files
These store data in readable format.
Examples:
• .txt
• .csv
• .json
4.2 Binary Files
These store data in binary format (0s and 1s).
Examples:
• .jpg
• .mp4
• .pdf
5. Opening a File
6. File Modes
Mode Description
r Read only
w Write (overwrites file)
a Append (adds data)
x Create new file
r+ Read and Write
w+ Write and Read
Mode Description
a+ Append and Read
rb Read binary
wb Write binary
7. Explanation of Each Mode with Examples
7.1 Read Mode (r)
• Opens file for reading
• Error if file does not exist
7.2 Write Mode (w)
• Creates file if not exists
• Overwrites existing content
7.3 Append Mode (a)
• Adds data to end of file
7.4 Create Mode (x)
• Creates new file
• Error if file exists
7.5 Read and Write (r+)
7.6 Write and Read (w+)
7.7 Append and Read (a+)
7.8 Binary Modes
8. File Handler
The variable used to store the file object is called a file handler.
Here, f is the file handler.
9. File Pointer
The file pointer indicates the current position in the file.
9.1 tell()
Returns current position:
9.2 seek()
Moves pointer to a specific position:
Example:
10. Reading Methods
read()
Reads entire file:
readline()
Reads one line:
readlines()
Reads all lines as list:
11. Writing Methods
12. Closing a File
Important to free memory and avoid errors.
13. Best Practice: Using with
Advantages:
• Automatically closes file
• Cleaner code
• Safer
14. Exception Handling
15. Real-Time Example
Saving Student Data
16. Data Science Example
17. Simple Analogy
Think of a file as a notebook:
Mode Meaning
r Read notebook
w Rewrite notebook
a Add new content
18. Important Points
• File = permanent storage
• File handler = object
• Pointer = position
• Use with for safety
• w deletes old data
• a adds data
19. Mini Practice Program
20. Summary
• File handling is used to store data permanently
• Different modes control file operations
• Use with statement for better coding practice
• Widely used in real-world applications