File handling allows you to create, read, write, update, and delete files using Python. It is one of the most important concepts for automation, data processing, and real-world Python applications. In this practice set, you’ll solve beginner-friendly file handling programs with complete solutions. Python File Handling Practice Questions with Solutions help to understand the concepts.
1. Python Program to Create and Write to a File
Problem Statement
Write a Python program to create a file named student.txt and write "Welcome to CodeMantra" into it.
Python Solution
file = open("student.txt", "w")
file.write("Welcome to CodeMantra")
file.close()
print("File created successfully.")
Sample Output
File created successfully.
Explanation
The "w" mode creates a new file if it doesn’t exist and writes data to it.
Concepts Covered
open()write()close()
2. Python Program to Read Data from a File
Problem Statement
Write a Python program to read the contents of student.txt.
Python Solution
file = open("student.txt", "r")
content = file.read()
print(content)
file.close()
Sample Output
Welcome to CodeMantra
Explanation
The read() method reads the complete contents of a file.
Concepts Covered
read()- Read Mode
3. Python Program to Append Data to a File
Problem Statement
Write a Python program to add "Python File Handling" to the end of student.txt.
Python Solution
file = open("student.txt", "a")
file.write("\nPython File Handling")
file.close()
print("Data appended successfully.")
Sample Output
Data appended successfully.
Explanation
The "a" mode appends new data without deleting existing content.
Concepts Covered
- Append Mode
write()
4. Python Program to Read a File Line by Line
Problem Statement
Write a Python program to read every line of a file.
Python Solution
file = open("student.txt", "r")
for line in file:
print(line.strip())
file.close()
Sample Output
Welcome to CodeMantra
Python File Handling
Explanation
The loop reads one line at a time from the file.
Concepts Covered
- for Loop
- Line-by-Line Reading
5. Python Program to Count the Number of Lines in a File
Problem Statement
Write a Python program to count the total number of lines in a file.
Python Solution
file = open("student.txt", "r")
count = len(file.readlines())
print("Total Lines:", count)
file.close()
Sample Output
Total Lines: 2
Explanation
The readlines() method returns all lines as a list.
Concepts Covered
readlines()len()
6. Python Program to Count the Number of Words in a File
Problem Statement
Write a Python program to count the total number of words in a file.
Python Solution
file = open("student.txt", "r")
content = file.read()
words = content.split()
print("Total Words:", len(words))
file.close()
Sample Output
Total Words: 5
Explanation
The file content is split into words, and len() counts them.
Concepts Covered
split()- Word Count
7. Python Program to Check Whether a File Exists
Problem Statement
Write a Python program to check whether student.txt exists.
Python Solution
import os
if os.path.exists("student.txt"):
print("File exists.")
else:
print("File not found.")
Sample Output
File exists.
Explanation
The os.path.exists() function checks whether the specified file is available.
Concepts Covered
os.path.exists()
8. Python Program to Copy the Contents of One File to Another
Problem Statement
Write a Python program to copy the contents of student.txt into backup.txt.
Python Solution
source = open("student.txt", "r")
destination = open("backup.txt", "w")
destination.write(source.read())
source.close()
destination.close()
print("File copied successfully.")
Sample Output
File copied successfully.
Explanation
The program reads data from one file and writes it into another.
Concepts Covered
- File Copy
read()write()
9. Python Program to Delete a File
Problem Statement
Write a Python program to delete backup.txt.
Python Solution
import os
if os.path.exists("backup.txt"):
os.remove("backup.txt")
print("File deleted successfully.")
else:
print("File not found.")
Sample Output
File deleted successfully.
Explanation
The os.remove() function deletes a file from the system.
Concepts Covered
os.remove()
10. Python Program to Read a File Using the with Statement
Problem Statement
Write a Python program to read a file using the with statement.
Python Solution
with open("student.txt", "r") as file:
print(file.read())
Sample Output
Welcome to CodeMantra
Python File Handling
Explanation
The with statement automatically closes the file after use, making the code cleaner and safer.
Concepts Covered
with- Context Manager
open()
11. Python Program to Count the Number of Words, Lines, and Characters in a File
Problem Statement
Write a Python program to count the total number of lines, words, and characters in a text file.
Python Solution
file = open("sample.txt", "r")
content = file.read()
file.close()
lines = content.split("\n")
words = content.split()
characters = len(content)
print("Total Lines:", len(lines))
print("Total Words:", len(words))
print("Total Characters:", characters)
Sample Output
Total Lines: 8
Total Words: 63
Total Characters: 412
Explanation
The program reads the complete file and calculates:
- Number of lines using
split("\n") - Number of words using
split() - Number of characters using
len()
Concepts Covered
- File Reading
- read()
- String Methods
- File Analysis
12. Python Program to Copy the Contents of One File to Another
Problem Statement
Write a Python program to copy all the contents of one text file into another file.
Python Solution
source = open("source.txt", "r")
destination = open("destination.txt", "w")
content = source.read()
destination.write(content)
source.close()
destination.close()
print("File copied successfully.")
Sample Output
File copied successfully.
Explanation
The program reads all the data from the source file and writes it into the destination file.
Concepts Covered
- File Reading
- File Writing
- read()
- write()
13. Python Program to Find the Longest Word in a File
Problem Statement
Write a Python program to find the longest word present in a text file.
Python Solution
file = open("sample.txt", "r")
words = file.read().split()
file.close()
longest = max(words, key=len)
print("Longest Word:", longest)
print("Length:", len(longest))
Sample Output
Longest Word: ArtificialIntelligence
Length: 22
Explanation
The program reads all words from the file and uses the max() function with key=len to find the longest word.
Concepts Covered
- File Reading
- max()
- Lambda Alternative
- String Processing
14. Python Program to Remove Blank Lines from a File
Problem Statement
Write a Python program to remove all blank lines from a text file and save the cleaned content into another file.
Python Solution
input_file = open("input.txt", "r")
output_file = open("cleaned.txt", "w")
for line in input_file:
if line.strip():
output_file.write(line)
input_file.close()
output_file.close()
print("Blank lines removed successfully.")
Sample Output
Blank lines removed successfully.
Explanation
The strip() method removes whitespace from a line. If the line is not empty after stripping, it is written to the new file.
Concepts Covered
- File Handling
- strip()
- Loops
- File Cleaning
15. Python Program to Count the Frequency of Every Word in a File
Problem Statement
Write a Python program to count how many times each word appears in a text file.
Python Solution
file = open("sample.txt", "r")
words = file.read().lower().split()
file.close()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print("Word Frequency:\n")
for word, count in frequency.items():
print(word, ":", count)
Sample Output
Word Frequency:
python : 6
is : 4
easy : 2
programming : 3
language : 2
Explanation
The program converts all words to lowercase, reads them into a list, and uses a dictionary to count the frequency of each word.
Concepts Covered
- File Reading
- Dictionaries
- Word Frequency Analysis
- get() Method
16. Python Program to Merge Two Text Files into a New File
Problem Statement
Write a Python program to merge the contents of two text files into a third file.
Python Solution
file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")
merged = open("merged.txt", "w")
merged.write(file1.read())
merged.write("\n")
merged.write(file2.read())
file1.close()
file2.close()
merged.close()
print("Files merged successfully.")
Sample Output
Files merged successfully.
Explanation
The program reads data from two separate files and writes both contents into a newly created file.
Concepts Covered
- File Reading
- File Writing
- Multiple Files
- File Merge
17. Python Program to Find Duplicate Lines in a File
Problem Statement
Write a Python program to identify and display duplicate lines present in a text file.
Python Solution
file = open("sample.txt", "r")
lines = file.readlines()
file.close()
seen = set()
duplicates = set()
for line in lines:
line = line.strip()
if line in seen:
duplicates.add(line)
else:
seen.add(line)
print("Duplicate Lines:")
for line in duplicates:
print(line)
Sample Output
Duplicate Lines:
Python is easy.
Practice daily.
Explanation
The program stores previously encountered lines in a set. If a line appears again, it is added to the duplicate set.
Concepts Covered
- File Handling
- Sets
- Duplicate Detection
- readlines()
18. Python Program to Read a File Line by Line with Line Numbers
Problem Statement
Write a Python program to display each line of a text file along with its corresponding line number.
Python Solution
file = open("sample.txt", "r")
for line_number, line in enumerate(file, start=1):
print(f"{line_number}: {line.strip()}")
file.close()
Sample Output
1: Python is easy.
2: Learn programming daily.
3: Practice coding regularly.
4: Success comes with consistency.
Explanation
The enumerate() function automatically generates line numbers while iterating through the file.
Concepts Covered
- enumerate()
- File Reading
- Loops
- Line Numbering
19. Python Program to Find the Largest Line in a File
Problem Statement
Write a Python program to find the longest line in a text file based on the number of characters.
Python Solution
file = open("sample.txt", "r")
lines = file.readlines()
file.close()
largest = max(lines, key=len)
print("Longest Line:")
print(largest)
print("Length:", len(largest))
Sample Output
Longest Line:
Python is one of the most popular programming languages in the world.
Length: 67
Explanation
The program reads all lines into a list and uses the max() function with key=len to determine the longest line.
Concepts Covered
- File Handling
- readlines()
- max()
- String Length
20. Python Program to Count Uppercase, Lowercase, Digits, and Special Characters in a File
Problem Statement
Write a Python program to count uppercase letters, lowercase letters, digits, and special characters present in a text file.
Python Solution
file = open("sample.txt", "r")
content = file.read()
file.close()
uppercase = 0
lowercase = 0
digits = 0
special = 0
for character in content:
if character.isupper():
uppercase += 1
elif character.islower():
lowercase += 1
elif character.isdigit():
digits += 1
elif not character.isspace():
special += 1
print("Uppercase Letters:", uppercase)
print("Lowercase Letters:", lowercase)
print("Digits:", digits)
print("Special Characters:", special)
Sample Output
Uppercase Letters: 18
Lowercase Letters: 246
Digits: 15
Special Characters: 32
Explanation
The program reads the entire file and checks each character using built-in string methods such as isupper(), islower(), isdigit(), and isspace() to classify it into different categories.
Concepts Covered
- File Reading
- Character Classification
- String Methods
- Data Analysis
21. Python Program to Create a Student Report Card from a CSV File
Problem Statement
Write a Python program to read student records from a CSV file, calculate the total marks, average marks, and grade for each student, and display the report.
Python Solution
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
print("Student Report Card\n")
for row in reader:
math = int(row["Math"])
science = int(row["Science"])
english = int(row["English"])
total = math + science + english
average = total / 3
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
elif average >= 60:
grade = "C"
else:
grade = "D"
print("Name:", row["Name"])
print("Total:", total)
print("Average:", round(average, 2))
print("Grade:", grade)
print("-" * 30)
Sample CSV File (students.csv)
Name,Math,Science,English
Rahul,85,90,88
Priya,95,96,94
Aman,72,80,76
Sample Output
Student Report Card
Name: Rahul
Total: 263
Average: 87.67
Grade: B
------------------------------
Name: Priya
Total: 285
Average: 95.0
Grade: A
------------------------------
Name: Aman
Total: 228
Average: 76.0
Grade: B
------------------------------
Explanation
The program reads data from a CSV file using csv.DictReader(), calculates the result for each student, and displays a formatted report.
Concepts Covered
- CSV File Handling
- DictReader
- File Reading
- Data Processing
22. Python Program to Generate an Error Log File
Problem Statement
Write a Python program that catches division errors and stores them in a log file.
Python Solution
try:
number = int(input("Enter a number: "))
result = 100 / number
print("Result =", result)
except Exception as error:
with open("error_log.txt", "a") as file:
file.write(str(error) + "\n")
print("Error saved to log file.")
Sample Output
Enter a number: 0
Error saved to log file.
Sample error_log.txt
division by zero
Explanation
Whenever an exception occurs, the program appends the error message to error_log.txt, making it useful for debugging real-world applications.
Concepts Covered
- Exception Handling
- File Append Mode
- Logging
- with Statement
23. Python Program to Search for a Word in Multiple Files
Problem Statement
Write a Python program to search for a specific word in multiple text files and display the file names where the word is found.
Python Solution
files = [
"file1.txt",
"file2.txt",
"file3.txt"
]
keyword = input("Enter word to search: ").lower()
for filename in files:
with open(filename, "r") as file:
content = file.read().lower()
if keyword in content:
print(keyword, "found in", filename)
Sample Output
Enter word to search: python
python found in file1.txt
python found in file3.txt
Explanation
The program loops through multiple files, reads each file, and checks whether the specified keyword exists.
Concepts Covered
- Multiple File Handling
- Search Operation
- Loops
- String Matching
24. Python Program to Backup a File Automatically
Problem Statement
Write a Python program to create a backup copy of an existing file.
Python Solution
with open("report.txt", "r") as original:
content = original.read()
with open("report_backup.txt", "w") as backup:
backup.write(content)
print("Backup created successfully.")
Sample Output
Backup created successfully.
Explanation
The program copies all contents from the original file into another file, creating a simple backup.
Concepts Covered
- File Copy
- File Reading
- File Writing
- Backup System
25. Python Program to Create a Simple Employee Attendance System
Problem Statement
Write a Python program to record employee attendance in a text file and display all attendance records.
Python Solution
employee = input("Enter Employee Name: ")
status = input("Enter Attendance (Present/Absent): ")
with open("attendance.txt", "a") as file:
file.write(f"{employee} - {status}\n")
print("\nAttendance Saved Successfully.\n")
print("Attendance Records:\n")
with open("attendance.txt", "r") as file:
print(file.read())
Sample Output
Enter Employee Name: Rahul
Enter Attendance (Present/Absent): Present
Attendance Saved Successfully.
Attendance Records:
Rahul - Present
Priya - Present
Aman - Absent
Explanation
The program appends employee attendance to a text file and then displays all saved attendance records. This demonstrates a practical use of file handling for maintaining persistent data.
Concepts Covered
- File Append Mode
- File Reading
- Real-World Project
- Data Storage
- Text File Management
Frequently Asked Questions (FAQs)
1. What is file handling in Python?
File handling in Python is the process of creating, opening, reading, writing, updating, and deleting files. It allows programs to store data permanently instead of keeping it only in memory.
Example:
file = open("sample.txt", "r")
print(file.read())
file.close()
Concepts Covered
- File Handling
- open()
- read()
- close()
2. What are the different file modes available in Python?
Python provides several file modes for different operations.
| Mode | Description |
|---|---|
r | Read a file (default mode) |
w | Write to a file (overwrites existing content) |
a | Append data to the end of a file |
x | Create a new file (fails if the file already exists) |
rb | Read a binary file |
wb | Write to a binary file |
r+ | Read and write |
a+ | Append and read |
Choose the appropriate mode based on the operation you want to perform.
3. What is the difference between read(), readline(), and readlines()?
These methods are used to read data from a file in different ways.
Example:
file = open("sample.txt", "r")
print(file.read()) # Reads the entire file
file.seek(0)
print(file.readline()) # Reads one line
file.seek(0)
print(file.readlines()) # Reads all lines into a list
file.close()
Difference
read()→ Reads the complete file.readline()→ Reads one line at a time.readlines()→ Reads all lines and returns a list.
4. Why should we use the with statement while working with files?
The with statement automatically closes the file after the operation is completed, even if an exception occurs. This makes the code cleaner and safer.
Example:
with open("sample.txt", "r") as file:
print(file.read())
Using with is considered a best practice in Python file handling.
5. What is the difference between write mode (w) and append mode (a)?
Write Mode (w) | Append Mode (a) |
|---|---|
| Overwrites existing content | Adds data at the end of the file |
| Creates a new file if it doesn’t exist | Also creates a new file if it doesn’t exist |
| Previous data is lost | Previous data remains unchanged |
Example:
with open("sample.txt", "a") as file:
file.write("Learning Python File Handling.\n")
6. What is the purpose of seek() and tell() in Python?
seek()moves the file pointer to a specific position.tell()returns the current position of the file pointer.
Example:
with open("sample.txt", "r") as file:
print(file.tell())
file.seek(5)
print(file.tell())
print(file.read())
These methods are useful when working with large files or random file access.
7. How can you check whether a file exists in Python?
The os.path.exists() function can be used to check whether a file exists before opening it.
Example:
import os
if os.path.exists("sample.txt"):
print("File Exists")
else:
print("File Not Found")
This helps prevent FileNotFoundError.
8. What are binary files in Python?
Binary files store data in binary format instead of plain text. They are commonly used for images, videos, PDFs, audio files, and executable files.
Example:
with open("photo.jpg", "rb") as file:
data = file.read()
print("Binary file read successfully.")
Binary files use modes such as rb, wb, and ab.
9. How can exceptions be handled while working with files?
Python uses try-except blocks to handle file-related errors gracefully.
Example:
try:
with open("sample.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found.")
Common file-related exceptions include:
FileNotFoundErrorPermissionErrorIsADirectoryErrorUnicodeDecodeErrorIOError
10. Why is file handling important in Python interviews and real-world projects?
File handling is a fundamental Python skill because most real-world applications need to store and retrieve data from files.
Common interview topics include:
- Reading and writing text files
- CSV file handling
- Binary files
- Exception handling
- File modes
- Context manager (
with) - File pointers (
seek()andtell()) - Log file processing
- Report generation
- Data backup and restoration
File handling is widely used in Data Science, Machine Learning, Automation, Web Development, ETL pipelines, Backend Development, Banking Systems, Inventory Management, Log Analysis, and Software Engineering. Mastering file handling enables you to build reliable applications that can efficiently manage persistent data and is an essential skill for Python developers and coding interviews.
Chapter Summary
After completing this chapter, you have learned:
- Creating files
- Reading files
- Writing files
- Appending data
- Reading files line by line
- Counting lines
- Counting words
- Checking file existence
- Copying files
- Deleting files
- Using the
withstatement
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
