Python File Handling Notes with Programs (Text, Binary, CSV)
1. Introduction to Files
A file is used to store data permanently on a computer. When a Python program runs, data
is stored in RAM temporarily.
To save data permanently, we use files.
Types of files:
1. Text File – stores human readable text
2. Binary File – stores data in binary format (0 and 1)
3. CSV File – stores tabular data separated by commas
2. Opening and Closing Files
Syntax:
file = open("filename", "mode")
Modes:
r - read
w - write (overwrites existing file)
a - append
r+ - read and write
w+ - write and read
a+ - append and read
Example:
file = open("[Link]","w")
[Link]("Hello Python")
[Link]()
3. Reading from Text File
Example program:
file = open("[Link]","r")
data = [Link]()
print(data)
[Link]()
read() -> reads entire file
readline() -> reads one line
readlines() -> reads all lines and returns list
4. Writing Multiple Lines
file = open("[Link]","w")
lines = ["Rahul 85\n","Amit 90\n","Riya 88\n"]
[Link](lines)
[Link]()
5. Append Data
file = open("[Link]","a")
[Link]("Neha 92\n")
[Link]()
6. Using with Statement
with open("[Link]","r") as file:
data = [Link]()
print(data)
The file automatically closes after execution.
7. Binary File using Pickle
Binary files store data in machine format.
Example to write binary data:
import pickle
file = open("[Link]","wb")
student = ["Rahul",85,"Delhi"]
[Link](student,file)
[Link]()
8. Reading Binary File
import pickle
file = open("[Link]","rb")
data = [Link](file)
print(data)
[Link]()
9. CSV File (Comma Separated Values)
CSV files store tabular data separated by commas.
Example CSV data:
Name,Marks,City
Rahul,85,Delhi
Amit,90,Mumbai
10. Writing CSV File
import csv
file = open("[Link]","w",newline="")
writer = [Link](file)
[Link](["Name","Marks","City"])
[Link](["Rahul",85,"Delhi"])
[Link](["Amit",90,"Mumbai"])
[Link]()
11. Reading CSV File
import csv
file = open("[Link]","r")
reader = [Link](file)
for row in reader:
print(row)
[Link]()
Important Exam Points
1. open() is used to open a file
2. close() closes the file
3. read(), readline(), readlines() read data
4. write(), writelines() write data
5. pickle module is used for binary files
6. csv module is used for CSV files