Python File Read and Write
1. Opening a File
Python uses the open() function to open files.
file = open (" filename . txt " , " mode ")
Common Modes
Mode Description
r Read (file must exist)
w Write (creates file or overwrites)
a Append (adds data at end)
r+ Read and Write
w+ Write and Read (overwrites)
a+ Append and Read
A better way to open files is using the with block:
with open (" filename . txt " , " mode ") as f :
This automatically closes the file.
2. Writing to a File
Example 1: Write Text
with open (" sample . txt " , " w ") as f :
f . write (" Hello students !\ n ")
f . write (" This is a Python file handling tutorial .")
Example 2: Write Multiple Lines
lines = [" Line 1\ n " , " Line 2\ n " , " Line 3\ n "]
with open (" multi . txt " , " w ") as f :
f . writelines ( lines )
1
3. Reading from a File
Example 1: Read Entire File
with open (" sample . txt " , " r ") as f :
data = f . read ()
print ( data )
Example 2: Read Line by Line
with open (" sample . txt " , " r ") as f :
for line in f :
print ( line . strip () )
Example 3: Read First Line
with open (" sample . txt " , " r ") as f :
line = f . readline ()
print ( line )
Example 4: Read All Lines into a List
with open (" sample . txt " , " r ") as f :
lines = f . readlines ()
print ( lines )
4. Appending to a File
with open (" sample . txt " , " a ") as f :
f . write ("\ nThis line is appended at the end .")
5. Checking if a File Exists
import os
if os . path . exists (" sample . txt ") :
print (" File found !")
else :
print (" File does not exist .")
2
6. File Handling with Exception Handling
try :
with open (" data . txt " , " r ") as f :
print ( f . read () )
except Fi leNotF oundEr ror :
print (" Error : File not found !")
7. Practical Examples
Example: Writing and Reading Student Marks
Write to File:
marks = {" Rahul ": 85 , " Anita ": 92 , " Sam ": 77}
with open (" marks . txt " , " w ") as f :
for name , score in marks . items () :
f . write ( f "{ name }: { score }\ n ")
Read from File:
with open (" marks . txt " , " r ") as f :
print ( f . read () )
8. Assignments
Assignment 1: Word Count Program
Write a Python program to:
• Read a text file
• Count the occurrences of each word
• Write the results to [Link]
Assignment 2: Student Records
Given a file [Link]:
Rahul,85
Anita,92
Sam,77
Write a program to:
• Read the file into a dictionary
• Print students who scored above 80
• Append their names to [Link]
3
Assignment 3 (Bonus)
Create a program that:
• Takes 5 product names and prices from the user
• Stores them in a dictionary
• Writes them to [Link]
• Reads the file and calculates the total bill