Python File Handling Practice Programs (with Solutions)
1. Program to Read Entire File using read()
Problem 1: Write a Python program to open a file and display the entire
content using read().
Solution
# Open file in read mode
file = open("[Link]", "r")
# Read entire file
content = [Link]()
# Display content
print(content)
# Close file
[Link]()
2. Program to Read File Line by Line using readline()
Problem: Write a program to read the first two lines of a file using
readline().
Solution
file = open("[Link]", "r")
line1 = [Link]()
line2 = [Link]()
print("First Line:", line1)
print("Second Line:", line2)
[Link]()
3. Program to Read All Lines using readlines()
Problem: Write a program to read all lines from a file using readlines()
and print them.
Solution
file = open("[Link]", "r")
lines = [Link]()
for line in lines:
print(line)
[Link]()
4. Program to Write Data to a File using write()
Problem: Write a Python program to create a file and write student
information into it.
Solution
file = open("[Link]", "w")
[Link]("Name: Rohan\n")
[Link]("Course: BCA\n")
[Link]("Marks: 85\n")
print("Data written successfully")
[Link]()
5. Program to Append Data to an Existing File
Problem: Write a program to add new data at the end of an existing file
using append mode.
Solution
file = open("[Link]", "a")
[Link]("City: Delhi\n")
[Link]("Grade: A\n")
print("Data appended successfully")
[Link]()
6. Program to Count Number of Lines in a File
Problem
Write a Python program to count the number of lines in a file.
Solution
file = open("[Link]", "r")
lines = [Link]()
print("Total number of lines:", len(lines))
[Link]()
7. Program to Count Words in a File
Problem
Write a program to count the number of words in a file.
Solution
file = open("[Link]", "r")
data = [Link]()
words = [Link]()
print("Total words:", len(words))
[Link]()
8. Program to Copy Content from One File to Another
Problem
Write a Python program to copy data from one file to another.
Solution
source = open("[Link]", "r")
destination = open("[Link]", "w")
content = [Link]()
[Link](content)
print("File copied successfully")
[Link]()
[Link]()
9. Program to Display File Line Number with Content
Problem
Write a program to display each line of a file with its line number.
Solution
file = open("[Link]", "r")
lines = [Link]()
for i in range(len(lines)):
print(i+1, ":", lines[i])
[Link]()
10. Program to Write Multiple Lines in File using List
Problem
Write a program to write multiple lines in a file using writelines().
Solution
file = open("[Link]", "w")
lines = [
"Python Programming\n",
"File Handling Example\n",
"Learning Python\n"
]
[Link](lines)
print("Lines written successfully")
[Link]()
Bonus (Best Practice) – Using with Statement
Problem
Write a program to read file safely using with statement.
Solution
with open("[Link]", "r") as file:
content = [Link]()
print(content)