File Handling in Python
Hey there! In this guide, we'll explore File Handling in Python. It covers the essentials of file handling in Python—from opening and closing files to reading, writing, and managing errors. Let's dive in!
File Handling in Python
File handling in Python allows programs to create, read, write, update, and manage files stored on a computer. It is an essential concept used in applications such as:
- Saving user data
- Reading configuration files
- Processing logs
- Working with CSV or text files
- Storing reports and outputs
Python provides built-in functions and methods that make file handling simple and efficient.
Video Explanation

1. Introduction to Files
A file is a collection of data stored permanently on a storage device.
Examples:
notes.txtdata.csvreport.pdf
Python mainly works with:
- Text files (
.txt,.csv,.json) - Binary files (
.jpg,.png,.exe)
2. Opening a File
Python uses the open() function to work with files.
Syntax:
file_object = open(file_name, mode)
Parameters:
| Parameter | Description |
|---|---|
file_name | Name or path of the file |
mode | Specifies how the file will be used |
3. File Modes
| Mode | Description |
|---|---|
r | Read mode |
w | Write mode (overwrites file) |
a | Append mode |
x | Create new file |
b | Binary mode |
t | Text mode |
r+ | Read and write |
4. Reading Files
4.1 Reading Entire File
Example:
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()
Explanation:
open("sample.txt", "r")opens the file in read mode.read()reads the entire file content.close()closes the file.
4.2 Reading Line by Line
Example:
file = open("sample.txt", "r")
for line in file:
print(line)
file.close()
Explanation:
- The loop reads one line at a time.
- Useful for large files.
4.3 Using readline()
Example:
file = open("sample.txt", "r")
print(file.readline())
print(file.readline())
file.close()
Explanation:
readline()reads one line at a time.- Each call moves to the next line.
5. Writing to Files
5.1 Write Mode (w)
Example:
file = open("sample.txt", "w")
file.write("Hello, Python!\n")
file.write("File handling example.")
file.close()
Explanation:
wmode creates the file if it does not exist.- If the file already exists, its contents are overwritten.
5.2 Append Mode (a)
Example:
file = open("sample.txt", "a")
file.write("\nNew line added.")
file.close()
Explanation:
amode adds content to the end of the file.- Existing data is preserved.
6. Creating a New File
Example:
file = open("newfile.txt", "x")
file.close()
Explanation:
- Creates a new file.
- Gives an error if the file already exists.
7. Closing Files
Closing a file:
- Saves changes properly
- Frees system resources
- Prevents file corruption
Example:
file = open("sample.txt", "r")
print(file.read())
file.close()