This article provides 34 Python File Handling practice questions with solutions.
Across all 34 exercises, core concepts like file opening, reading, writing, appending, and error handling are covered first. Then it moves into text analysis, string manipulation, line searching, and OS-level file operations such as renaming, deleting, copying, and directory management. Finally, it covers data handling through binary files, large file chunking, and keyword-based filtering.
Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.
- All solutions have been fully tested on Python 3.
- Use our Online Code Editor to solve these exercises in real time.
- If you have other solutions, please share them in the comments to help fellow developers.
Also, See:
- Python Exercises: A set of 20 topic specific exercises
- Python File Handling: Master Python File Handling to solve these exercises
+ Table Of Contents (34 Exercises)
Table of contents
- Exercise 1: Write User Name to File
- Exercise 2: Read and Print Complete File
- Exercise 3: Read File Line by Line Using Loop
- Exercise 4: Read File Lines into a List
- Exercise 5: Append New Sentence to Existing File
- Exercise 6: Clear All File Content
- Exercise 7: Write Text to New File
- Exercise 8: Check If File Exists
- Exercise 9: Handle Missing File with Try-Except
- Exercise 10: Count Total Lines in File
- Exercise 11: Count Total Words in File
- Exercise 12: Count Total Characters in File
- Exercise 13: Count Specific Word Occurrences in File
- Exercise 14: Read Only First N Lines
- Exercise 15: Read Only Last N Lines
- Exercise 16: Read Specific Line Numbers from File
- Exercise 17: Find Longest Word in File
- Exercise 18: Count Each Letter Frequency in File
- Exercise 19: Search Word and Print Matching Line Numbers
- Exercise 20: Strip Extra Whitespace and Save to New File
- Exercise 21: Convert Uppercase to Lowercase and Vice Versa
- Exercise 22: Find and Replace a Word Throughout File
- Exercise 23: Get File Size in Kilobytes
- Exercise 24: Copy File Using Binary Mode
- Exercise 25: Rename a Single File
- Exercise 26: Rename Multiple Files with Prefix
- Exercise 27: Delete a File from Disk
- Exercise 28: Merge Two Files into One
- Exercise 29: Reverse Line Order and Save to New File
- Exercise 30: List All Files in Directory and Save
- Exercise 31: Read and Write Binary Image File
- Exercise 32: Extract and Sort Unique Words from File
- Exercise 33: Filter Log File Lines Containing ERROR Keyword
- Exercise 34: Split Large File into Smaller 10-Line Files
Exercise 1: Write User Name to File
Problem Statement: Write a Python program that accepts a user’s name as input and writes it to a file called user.txt.
Purpose: This exercise introduces you to writing data to a file using Python’s built-in open() function with write mode. It covers how user input can be persisted to disk, a fundamental concept in data storage and logging.
Given Input: User enters their name at runtime, e.g. Alice
Expected Output: A file named user.txt is created containing the entered name, e.g. Alice
Refer: Write to File Python
▼ Hint
- Use
input()to read the user’s name from the console. - Open the file with
open("user.txt", "w")to open it in write mode. - Use the
write()method on the file object to save the name. - Always close the file after writing, or use a
withstatement to handle it automatically.
▼ Solution & Explanation
Explanation:
input("Enter your name: "): Prompts the user to type their name and stores it in the variablename.open("user.txt", "w"): Opens (or creates)user.txtin write mode. If the file already exists, its contents are overwritten.withstatement: Ensures the file is properly closed after the block exits, even if an error occurs. This is the preferred pattern for file operations.f.write(name): Writes the string value ofnameinto the file without adding a newline automatically.
Exercise 2: Read and Print Complete File
Problem Statement: Write a Python program that opens a file called data.txt and prints its entire contents to the console.
Purpose: This exercise teaches you how to open an existing file in read mode and retrieve all of its contents at once using read(). It is a foundational skill for processing configuration files, logs, and data files.
Given Input: A file named data.txt containing: Hello, World!
Expected Output: Hello, World!
Refer: Read File in Python
▼ Hint
- Open the file using
open("data.txt", "r")— the"r"flag stands for read mode and is the default. - Use the
read()method to load all file contents into a single string. - Print the result using
print(). - Use a
withblock to ensure the file is closed after reading.
▼ Solution & Explanation
Explanation:
open("data.txt", "r"): Opens the file in read mode. Python raises aFileNotFoundErrorif the file does not exist.f.read(): Reads the entire file as a single string, including newline characters. This is suitable for small files where loading all content at once is not a memory concern.print(content): Outputs the string to the console. Becauseread()preserves newlines, the output mirrors the original file layout.
Exercise 3: Read File Line by Line Using Loop
Problem Statement: Write a Python program that reads a file called lines.txt and prints each line one at a time using a loop.
Purpose: This exercise shows how to iterate over a file object directly, which is memory-efficient for large files. It is a common pattern used when processing log files, CSVs, or any line-structured text data.
Given Input: A file named lines.txt containing:
Line 1 Line 2 Line 3
Expected Output:
Line 1 Line 2 Line 3
▼ Hint
- Open the file with
open("lines.txt", "r")inside awithblock. - You can loop over the file object directly:
for line in f— Python reads one line per iteration. - Each
lineincludes a trailing\nnewline character. Useline.strip()if you want to remove it before printing.
▼ Solution & Explanation
Explanation:
for line in f: Iterates over the file object line by line. Python reads each line lazily, making this approach memory-efficient for very large files.line: Each iteration yields a string that includes the trailing newline character\nfrom the file.print(line, end=""): Prints the line without adding an extra newline, since the line already contains one. This prevents double-spacing in the output.- Alternative: Use
line.strip()and a regularprint(line.strip())to remove the trailing newline explicitly before printing.
Exercise 4: Read File Lines into a List
Problem Statement: Write a Python program that reads all lines from a file called items.txt into a list and prints the list.
Purpose: This exercise demonstrates how to load structured line-based file data into a Python list for further processing. This pattern is widely used when reading configuration entries, word lists, or simple datasets from files.
Given Input: A file named items.txt containing:
apple banana cherry
Expected Output: ['apple\n', 'banana\n', 'cherry']
▼ Hint
- Open the file in read mode with a
withblock. - Use
f.readlines()to return a list where each element is one line from the file. - Note that each line will include the trailing
\ncharacter. If you want clean strings, use a list comprehension with.strip().
▼ Solution & Explanation
Explanation:
f.readlines(): Reads all lines from the file and returns them as a list of strings. Each string corresponds to one line and retains the\nnewline character at the end.lines: Stores the resulting list, which you can index, slice, or iterate over just like any Python list.- Alternative: Use
[line.strip() for line in f.readlines()]to get a clean list without newline characters, which is more convenient for most downstream processing.
Exercise 5: Append New Sentence to Existing File
Problem Statement: Write a Python program that appends the sentence This is a new line. to an existing file called notes.txt without overwriting its current content.
Purpose: This exercise teaches the difference between write mode and append mode. Append mode is essential when you need to add entries to a log file, journal, or any growing data file without destroying previously stored content.
Given Input: A file named notes.txt already containing: Original content.
Expected Output: File now contains:
Original content. This is a new line.
▼ Hint
- Use
open("notes.txt", "a")to open the file in append mode. The"a"flag positions the write cursor at the end of the file. - Use
f.write("\nThis is a new line.")to add a newline before the new sentence so it appears on its own line. - If you use
"w"by mistake, the existing content will be deleted.
▼ Solution & Explanation
Explanation:
open("notes.txt", "a"): Opens the file in append mode. If the file does not exist, Python creates it. Existing content is never overwritten.f.write("\nThis is a new line."): The leading\nensures the new sentence begins on a fresh line rather than being joined to the last character of the existing content.- Key distinction:
"a"(append) vs"w"(write) – using"w"here would erase all existing content before writing, which is a common and hard-to-notice mistake.
Exercise 6: Clear All File Content
Problem Statement: Write a Python program that clears all content from an existing file called temp.txt, leaving it as an empty file.
Purpose: This exercise illustrates how opening a file in write mode truncates it immediately. Understanding this behavior is important to avoid accidental data loss and also useful when you intentionally need to reset a file, such as clearing a cache or resetting a log.
Given Input: A file named temp.txt containing some existing text, e.g. Some old data.
Expected Output: temp.txt exists but is completely empty (0 bytes).
▼ Hint
- Opening a file with
open("temp.txt", "w")and writing nothing to it truncates the file to zero bytes. - You do not need to call
write()at all. Simply opening in write mode is enough to clear the file. - Alternatively, you can use
f.truncate(0)after opening in"r+"mode for more explicit control.
▼ Solution & Explanation
Explanation:
open("temp.txt", "w"): Opening a file in write mode immediately truncates it to zero length. This happens before anywrite()call is made.pass: A no-operation placeholder that makes thewithblock syntactically valid. No data is written, so the file ends up empty.- Alternative:
open("temp.txt", "w").close()achieves the same result in a single line, though thewithpattern is safer and more explicit.
Exercise 7: Write Text to New File
Problem Statement: Write a Python program that creates a new file called output.txt and writes three lines of text to it.
Purpose: This exercise reinforces writing multiple lines to a file and understanding how newline characters work in file output. It is a practical skill used in generating reports, saving results, and creating data export files programmatically.
Given Input: No external input. The three lines to write are predefined in the program.
Expected Output: A file named output.txt containing:
First line Second line Third line
▼ Hint
- Open the file with
open("output.txt", "w"). - Use multiple
f.write()calls, each ending with\n, to write each line separately. - Alternatively, use
f.writelines()with a list of strings, making sure each string ends with\n.
▼ Solution & Explanation
Explanation:
lines: A list of strings where each item represents one line. The\nat the end of each string is required becausewritelines()does not add newlines automatically.f.writelines(lines): Writes all strings in the list to the file in sequence. It is equivalent to callingf.write()once per item but more concise.- Alternative: Use three separate
f.write("First line\n")calls for clarity, or useprint("First line", file=f)which adds the newline automatically.
Exercise 8: Check If File Exists
Problem Statement: Write a Python program that checks whether a file called data.txt exists in the current directory and prints an appropriate message based on the result.
Purpose: This exercise introduces the os.path module (or the modern pathlib alternative) for checking file existence before performing operations on it. This is a defensive programming practice that prevents crashes caused by attempting to open files that do not exist.
Given Input: The filename data.txt is hardcoded. The file may or may not be present.
Expected Output: File exists. if the file is present, or File does not exist. if it is not.
Refer: Python Check If File Exists
▼ Hint
- Import the
osmodule at the top of your program. - Use
os.path.exists("data.txt")which returnsTrueif the file (or directory) exists, andFalseotherwise. - Wrap this in an
if/elseblock to print the appropriate message. - As a modern alternative, you can use
from pathlib import Pathand check withPath("data.txt").exists().
▼ Solution & Explanation
Explanation:
import os: Imports Python’s built-inosmodule, which provides functions for interacting with the operating system, including the filesystem.os.path.exists("data.txt"): Checks whether the given path points to an existing file or directory. Returns a boolean:Trueif found,Falseif not.- Practical use: Always check for file existence before attempting to open a file in read mode. Without this check, your program will raise a
FileNotFoundErrorif the file is missing. - Modern alternative:
from pathlib import Pathfollowed byPath("data.txt").exists()achieves the same result with a more object-oriented and readable syntax, preferred in Python 3.4+.
Exercise 9: Handle Missing File with Try-Except
Problem Statement: Write a Python program that attempts to open a file called missing.txt and gracefully handles the case where the file does not exist using a try-except block.
Purpose: This exercise teaches you how to handle file-related exceptions in Python. Rather than letting your program crash with an unhandled error, you learn to anticipate failure conditions and respond with a meaningful message. This is essential for writing robust, production-ready file-handling code.
Given Input: The filename missing.txt is hardcoded. The file does not exist in the current directory.
Expected Output: Error: The file was not found.
▼ Hint
- Wrap the
open()call inside atryblock. - Catch the
FileNotFoundErrorexception in theexceptclause and print a user-friendly message. - You can also catch the broader
IOErrororOSErrorto handle other file-related issues like permission errors. - Optionally, add a
finallyblock to run cleanup code regardless of whether an error occurred.
▼ Solution & Explanation
Explanation:
tryblock: Contains the code that might raise an exception. Python attempts to execute it, and if an error occurs, execution jumps immediately to the matchingexceptclause.FileNotFoundError: A built-in Python exception raised specifically when a file or directory is requested but cannot be found at the given path.except FileNotFoundError: Catches only this specific error type, allowing other unexpected exceptions to still surface. This is more precise than using a bareexceptclause.- Alternative: Add
except PermissionErroras a second clause to also handle cases where the file exists but the user lacks read permission.
Exercise 10: Count Total Lines in File
Problem Statement: Write a Python program that opens a file called data.txt and counts the total number of lines it contains.
Purpose: This exercise practices reading a file and applying counting logic to its contents. Line counting is a common task in log analysis, data validation, and text processing pipelines where you need to know the size or shape of a file before processing it.
Given Input: A file named data.txt containing:
Hello World Python File Handling
Expected Output: Total lines: 4
Refer: Python Count Number of Lines in a File
▼ Hint
- Open the file and use
readlines()to get a list of all lines, then uselen()on the result. - Alternatively, loop over the file object with a counter variable that increments on each iteration.
- A concise one-liner approach:
sum(1 for line in f)counts lines without loading the entire file into memory at once.
▼ Solution & Explanation
Explanation:
f.readlines(): Reads all lines from the file and returns them as a list of strings. Each element corresponds to one line, including its trailing\ncharacter.len(lines): Returns the number of elements in the list, which equals the number of lines in the file.- Edge case: If the last line of the file does not end with a newline, it is still counted as a line.
readlines()handles this correctly. - Memory-efficient alternative:
sum(1 for line in f)iterates lazily and is preferable for very large files where loading all lines into a list at once would be wasteful.
Exercise 11: Count Total Words in File
Problem Statement: Write a Python program that reads a file called data.txt and counts the total number of words across all its lines.
Purpose: This exercise builds on reading file content and applying string methods to analyse text. Word counting is a fundamental operation in text processing, search indexing, and natural language processing tasks.
Given Input: A file named data.txt containing:
Hello World Python is great File handling is easy
Expected Output: Total words: 9
▼ Hint
- Read the entire file content using
f.read(), then call.split()on the result to break it into a list of words. .split()with no arguments splits on any whitespace (spaces, tabs, newlines) and automatically ignores extra blank space.- Use
len()on the resulting list to get the word count.
▼ Solution & Explanation
Explanation:
f.read(): Reads the entire file into a single string, including newline characters between lines. This allowssplit()to work across all lines at once.content.split(): Splits the string at every whitespace boundary (spaces, tabs, and newlines) and returns a list of word tokens. It ignores leading, trailing, and consecutive whitespace automatically.len(words): Counts the total number of tokens in the list, which corresponds to the total word count in the file.- Note: This approach counts punctuation attached to words (e.g.,
great,) as a single token. For more precise word counting, consider stripping punctuation with thestringmodule or a regular expression.
Exercise 12: Count Total Characters in File
Problem Statement: Write a Python program that reads a file called data.txt and counts the total number of characters it contains, including spaces and newlines.
Purpose: This exercise demonstrates how to measure the size of text content at the character level. Character counting is useful in text editors, form validation, data compression analysis, and anywhere that the byte or character length of a file is relevant.
Given Input: A file named data.txt containing: Hello, World!
Expected Output: Total characters: 13
▼ Hint
- Read the entire file as a string using
f.read(). - Use the built-in
len()function on the resulting string to count all characters, including spaces and newline characters. - If you want to count only printable characters (excluding newlines), call
.replace("\n", "")on the content before passing it tolen().
▼ Solution & Explanation
Explanation:
f.read(): Loads the complete file content into a string variable. Every character in the file, including spaces, punctuation, and newline characters, is included.len(content): Returns the total number of characters in the string. In Python 3, this counts Unicode characters (code points), not raw bytes, which matters for files containing non-ASCII characters.- Newlines count: Each
\nat the end of a line is counted as one character. On Windows, files may use\r\n(two characters per line ending) unless opened in text mode, which Python normalises to\nby default. - Alternative: Use
len(content.replace("\n", ""))to exclude newline characters from the count, orlen(content.replace(" ", "").replace("\n", ""))to count only non-whitespace characters.
Exercise 13: Count Specific Word Occurrences in File
Problem Statement: Write a Python program that reads a file called data.txt and counts how many times the word Python appears in it.
Purpose: This exercise combines file reading with string search methods. Counting specific word or pattern occurrences is a core technique in log parsing, keyword analysis, content auditing, and search engine development.
Given Input: A file named data.txt containing:
Python is great. I love Python. Python makes file handling easy.
Expected Output: Occurrences of 'Python': 3
▼ Hint
- Read the entire file using
f.read(). - Use the string method
.count("Python")to count non-overlapping occurrences of the word in the content. - To make the search case-insensitive, convert the content to lowercase with
.lower()and search for the lowercase version of the word.
▼ Solution & Explanation
Explanation:
word_to_find = "Python": Stores the target word in a variable so it can be reused in both the search and the output message without repetition.content.count(word_to_find): Returns the number of non-overlapping occurrences of the substring within the full file content string. It is case-sensitive by default.- Case-insensitive variant: Use
content.lower().count(word_to_find.lower())to match regardless of capitalisation, sopython,Python, andPYTHONwould all be counted. - Note on substring matching:
.count()matches any occurrence, including within larger words. For example, searching foronwould also match insidePython. Usecontent.split().count(word)or theremodule with word boundary markers\bfor whole-word-only matching.
Exercise 14: Read Only First N Lines
Problem Statement: Write a Python program that reads and prints only the first 3 lines from a file called data.txt.
Purpose: This exercise teaches you how to limit file reading to a specific number of lines. This technique is critical when working with large files where reading the entire content is inefficient, such as previewing log files, inspecting dataset headers, or loading configuration sections.
Given Input: A file named data.txt containing:
Line 1 Line 2 Line 3 Line 4 Line 5
Expected Output:
Line 1 Line 2 Line 3
▼ Hint
- Use
f.readlines()to get all lines as a list, then slice the firstnelements using[:n]. - Alternatively, use a loop with a counter variable that stops after
niterations usingbreak. - The most memory-efficient approach for large files: use
itertools.islice(f, n)to read only the firstnlines without loading the rest into memory.
▼ Solution & Explanation
Explanation:
n = 3: Defines how many lines to read. Storing this in a variable makes the program easy to adapt without hunting through the code for hardcoded numbers.enumerate(f): Iterates over the file while providing a line indexistarting at 0, allowing you to track how many lines have been read so far.if i >= n: break: Stops reading as soon as the index reachesn. Because the file object is lazy, Python never reads the remaining lines from disk after thebreak.- Slice alternative:
f.readlines()[:n]is more concise but loads the entire file into memory first before slicing, which is inefficient for large files.
Exercise 15: Read Only Last N Lines
Problem Statement: Write a Python program that reads and prints only the last 3 lines from a file called data.txt.
Purpose: Reading the tail of a file is one of the most common real-world file operations, used extensively in log monitoring, debugging, and audit trail review. This exercise teaches you how to retrieve the most recent entries from a file efficiently.
Given Input: A file named data.txt containing:
Line 1 Line 2 Line 3 Line 4 Line 5
Expected Output:
Line 3 Line 4 Line 5
▼ Hint
- Use
f.readlines()to load all lines into a list, then use a negative slice[-n:]to extract the lastnlines. - Loop over the sliced result and print each line, using
end=""to avoid adding extra newlines since each line already ends with\n. - For very large files, consider the
collections.dequeapproach with a fixedmaxlento avoid loading the whole file into memory.
▼ Solution & Explanation
Explanation:
f.readlines(): Reads all lines into a list. While this loads the whole file, it is necessary here because you need access to the end of the file, which requires knowing where the end is.lines[-n:]: Python’s negative slicing returns the lastnelements of the list. Ifnis larger than the total number of lines, this safely returns all lines without raising an error.print(line, end=""): Prints each line as-is without appending an extra newline, since lines fromreadlines()already contain their trailing\n.- Memory-efficient alternative:
from collections import dequefollowed bydeque(f, maxlen=n)keeps only the lastnlines in memory as it streams through the file, ideal for very large files.
Exercise 16: Read Specific Line Numbers from File
Problem Statement: Write a Python program that reads a file called data.txt and prints only the lines at positions 1, 3, and 5 (using 1-based line numbering).
Purpose: This exercise teaches selective file reading by targeting specific line numbers. This pattern is useful when parsing structured files where particular lines carry known information, such as headers, metadata rows, or fixed-position records in a report.
Given Input: A file named data.txt containing:
Line 1 Line 2 Line 3 Line 4 Line 5
Expected Output:
Line 1 Line 3 Line 5
Refer: Read Specific Lines From a File in Python
▼ Hint
- Store the desired line numbers in a set or list, e.g.
target_lines = {1, 3, 5}. - Use
enumerate(f, start=1)to iterate over lines with 1-based numbering, and check whether the current line number is in your target set. - A set is preferred over a list for the targets because membership checks (
in) are O(1) for sets vs O(n) for lists.
▼ Solution & Explanation
Explanation:
target_lines = {1, 3, 5}: A Python set containing the 1-based line numbers to print. Using a set makes membership checks fast and the intent clear, and it is easy to update with different line numbers.enumerate(f, start=1): Iterates over the file object while providing a line counter that starts at 1 rather than the default 0, matching natural 1-based line numbering.if line_num in target_lines: Checks membership in the set for each line. Only lines whose number appears in the set are printed; all others are skipped.- Early exit optimisation: If your target lines are all near the top of a very large file, you can add
if line_num > max(target_lines): breakto stop reading once the last target line has been reached.
Exercise 17: Find Longest Word in File
Problem Statement: Write a Python program to read a text file and find the longest word present in it.
Purpose: This exercise strengthens your ability to read file content, split text into tokens, and apply comparison logic across a collection – skills useful in text analysis, NLP preprocessing, and content parsing tasks.
Given Input: A file words.txt containing: Python is a powerful programming language
Expected Output: Longest word: programming
▼ Hint
- Open the file and read its entire content using
.read(). - Use
.split()to break the text into a list of words. - Iterate through the list and track the word with the greatest
len(). - You can also use Python’s built-in
max(words, key=len)as a concise alternative.
▼ Solution & Explanation
Explanation:
f.read().split(): Reads the full file content as a string and splits it into a list of words using whitespace as the delimiter.longest = "": Initializes an empty string to hold the current longest word found during iteration.if len(word) > len(longest): Compares each word’s length against the current longest and updates it when a longer word is found.- Alternative:
max(words, key=len)achieves the same result in one line, but the loop makes the comparison logic explicit and easier to follow.
Exercise 18: Count Each Letter Frequency in File
Problem Statement: Write a Python program to read a text file and count how many times each letter of the alphabet appears in it.
Purpose: This exercise practises file reading, string filtering, and frequency counting using dictionaries – foundational techniques in text mining, cryptography, and data analysis.
Given Input: A file sample.txt containing: Hello World
Expected Output:
h: 1 e: 1 l: 3 o: 2 w: 1 r: 1 d: 1
▼ Hint
- Convert the entire file content to lowercase using
.lower()for case-insensitive counting. - Loop through each character and use
.isalpha()to skip spaces, digits, and punctuation. - Use a dictionary to store each letter as a key and its count as the value.
dict.get(char, 0) + 1is a clean way to increment a count even when the key does not yet exist.
▼ Solution & Explanation
Explanation:
f.read().lower(): Reads the entire file and converts it to lowercase so thatHandhare counted as the same letter.char.isalpha(): Filters out non-letter characters such as spaces, digits, and punctuation before counting.freq.get(char, 0) + 1: Retrieves the existing count for a letter (defaulting to 0 if absent) and increments it by 1, avoiding aKeyError.freq.items(): Iterates over key-value pairs in the dictionary to print each letter alongside its frequency.
Exercise 19: Search Word and Print Matching Line Numbers
Problem Statement: Write a Python program to search for a specific word in a file and print the line numbers where that word appears.
Purpose: This exercise builds skills in line-by-line file reading, string searching, and index tracking – useful in log analysis, debugging tools, and text search utilities.
Given Input: A file notes.txt where the word Python appears on lines 1 and 3, and the search term is Python.
Expected Output:
"Python" found on line 1 "Python" found on line 3
Refer: Python Search for a String in Text Files
▼ Hint
- Use
enumerate(f, start=1)when iterating over the file to get both the line number and the line content together. - Use the
inoperator to check whether the search word exists within a line. - Consider using
.lower()on both the line and the search word for a case-insensitive match.
▼ Solution & Explanation
Explanation:
enumerate(f, start=1): Iterates over the file object line by line while providing a counter that starts at 1, giving you the line number and content in each iteration.search_word.lower() in line.lower(): Converts both the search term and the current line to lowercase before comparison, making the search case-insensitive.f'"{search_word}" found on line {line_num}': Uses an f-string to format the output clearly, displaying both the word searched for and the line it was found on.
Exercise 20: Strip Extra Whitespace and Save to New File
Problem Statement: Write a Python program to read a text file, remove leading and trailing whitespace from each line, and save the cleaned content to a new file.
Purpose: This exercise practises reading, transforming, and writing file content line by line – a common pattern in data cleaning pipelines, log processing, and file preprocessing tasks.
Given Input: A file messy.txt with lines such as Hello World and Python
Expected Output: A new file clean.txt containing Hello World and Python, with all surrounding whitespace removed.
▼ Hint
- Open the input file for reading and the output file for writing simultaneously using two
with open()statements or a nestedwithblock. - Use
.strip()on each line to remove leading and trailing spaces and newline characters. - When writing each cleaned line to the output file, remember to append
\nmanually since.strip()removes the original newline.
▼ Solution & Explanation
Explanation:
open("messy.txt", "r") as infile, open("clean.txt", "w") as outfile: Opens both files in a singlewithstatement, ensuring both are properly closed after the block finishes.line.strip(): Removes all leading and trailing whitespace characters, including spaces, tabs, and the newline character at the end of each line.outfile.write(cleaned_line + "\n"): Writes the cleaned line to the output file and manually appends a newline character, since.strip()has already removed the original one.
Exercise 21: Convert Uppercase to Lowercase and Vice Versa
Problem Statement: Write a Python program to read a text file and swap the case of every letter – uppercase letters become lowercase and lowercase letters become uppercase – then save the result to a new file.
Purpose: This exercise practises string transformation methods and file read-write workflows, reinforcing how to apply character-level operations across entire file content.
Given Input: A file input.txt containing: Hello World
Expected Output: A new file swapped.txt containing: hELLO wORLD
▼ Hint
- Read the entire file content using
.read(). - Apply Python’s built-in
.swapcase()string method to toggle the case of every character at once. - Write the transformed string directly to a new output file.
▼ Solution & Explanation
Explanation:
infile.read(): Reads the entire file content into a single string, making it straightforward to apply a transformation to the whole text at once.content.swapcase(): Returns a new string where every uppercase letter is converted to lowercase and every lowercase letter is converted to uppercase. Non-letter characters remain unchanged.outfile.write(swapped): Writes the fully transformed string to the output file. Since the original newlines are preserved in the string, no manual\nis needed here.
Exercise 22: Find and Replace a Word Throughout File
Problem Statement: Write a Python program to read a text file, replace every occurrence of a specified word with a new word, and save the updated content back to the file.
Purpose: This exercise demonstrates a practical file update pattern – reading, modifying in memory, and writing back – used in configuration management, template engines, and automated text editing tools.
Given Input: A file story.txt containing I love Java. Java is great., with the goal of replacing Java with Python.
Expected Output: The file story.txt updated to: I love Python. Python is great.
▼ Hint
- Read the full file content into a string first, then close the file before reopening it for writing.
- Use the string
.replace(old, new)method to substitute all occurrences at once. - Open the same file again in write mode (
"w") to overwrite it with the updated content.
▼ Solution & Explanation
Explanation:
content = f.read(): Reads the entire file into memory as a string so all replacements can be made before any writing occurs.content.replace(old_word, new_word): Replaces every occurrence of the old word with the new word throughout the string. This method is case-sensitive, soJavaandjavawould be treated as different words.open("story.txt", "w"): Reopens the same file in write mode, which truncates (clears) the existing content before writing the updated string back.- Note: Reading and writing are done in two separate
withblocks intentionally. Opening a file in"r"and"w"at the same time can lead to data loss on some systems.
Exercise 23: Get File Size in Kilobytes
Problem Statement: Write a Python program to find and display the size of a given file in kilobytes (KB).
Purpose: This exercise introduces the os module for file system operations and practises unit conversion – skills used in file management utilities, upload validators, and storage monitoring tools.
Given Input: A file data.txt with a size of 2048 bytes.
Expected Output: File size: 2.0 KB
Refer: Python Check File Size
▼ Hint
- Import the
osmodule to access file system information. - Use
os.path.getsize(filename)to get the file size in bytes. - Divide the result by 1024 to convert bytes to kilobytes.
▼ Solution & Explanation
Explanation:
import os: Imports Python’s built-inosmodule, which provides functions for interacting with the operating system, including file and directory operations.os.path.getsize(filename): Returns the size of the specified file in bytes. It raises anOSErrorif the file does not exist or is inaccessible.size_bytes / 1024: Converts the size from bytes to kilobytes. Since Python 3 uses true division by default, this returns a float (e.g.,2.0), giving a precise result even for non-round values.- Note: For larger files, you can chain the conversion further: divide by
1024again to get megabytes, or use1024 ** 2directly.
Exercise 24: Copy File Using Binary Mode
Problem Statement: Write a Python program to copy the contents of one file to another using binary mode, so that the program works correctly for all file types including images, PDFs, and executables.
Purpose: This exercise introduces binary file I/O, which is essential for handling non-text files. It reinforces the read-then-write pattern while highlighting the difference between text mode and binary mode in Python.
Given Input: A source file source.txt (or any file type) to be copied to destination.txt.
Expected Output: A new file destination.txt created with identical content to source.txt, confirmed by printing File copied successfully.
Refer: Copy Files and Directories in Python
▼ Hint
- Open the source file in binary read mode using
"rb"and the destination file in binary write mode using"wb". - Use
.read()to load all the bytes from the source, then.write()to save them to the destination. - Binary mode ensures no character encoding conversion happens, making the copy exact regardless of file type.
▼ Solution & Explanation
Explanation:
open("source.txt", "rb"): Opens the source file in binary read mode. Thebflag tells Python to treat the file as raw bytes rather than decoded text, preventing any newline or encoding translations.open("destination.txt", "wb"): Opens (or creates) the destination file in binary write mode. If the file already exists, its content is overwritten.src.read(): Reads the entire file as abytesobject. This works for any file type since no decoding is applied.dst.write(data): Writes the raw bytes directly to the destination file, producing an exact byte-for-byte copy of the original.- Note: For very large files, reading in chunks (e.g.,
src.read(4096)in a loop) is more memory-efficient than reading everything at once.
Exercise 25: Rename a Single File
Problem Statement: Write a Python program to rename a single file on disk using the os module.
Purpose: This exercise introduces the os.rename() function for file system manipulation – a fundamental skill used in file management scripts, automated batch processors, and data pipeline utilities.
Given Input: An existing file named old_name.txt on disk.
Expected Output: File renamed successfully.
Refer: Rename Files in Python
▼ Hint
- Import the
osmodule to access file system functions. - Use
os.rename(old_name, new_name)to rename the file. Both arguments are strings representing the file paths. - Wrap the call in a
try-exceptblock to handle cases where the file does not exist (FileNotFoundError).
▼ Solution & Explanation
Explanation:
import os: Loads Python’s built-inosmodule, which provides an interface to operating system file and directory operations.os.rename(old_name, new_name): Renames the file at the path given by the first argument to the path given by the second. If both paths are on the same filesystem, this is an atomic operation on most systems.except FileNotFoundError: Catches the error raised when the source file does not exist, preventing the program from crashing and giving the user a clear message instead.- Note:
os.rename()can also move a file to a different directory by providing a full destination path, not just a new filename.
Exercise 26: Rename Multiple Files with Prefix
Problem Statement: Write a Python program to rename all .txt files in a directory by adding a specified prefix to each filename.
Purpose: This exercise combines directory listing, string manipulation, and file renaming in a loop – a pattern widely used in bulk file organisation, dataset preparation, and automated archiving workflows.
Given Input: A directory containing notes.txt and data.txt, with the prefix 2024_.
Expected Output:
Renamed: notes.txt -> 2024_notes.txt Renamed: data.txt -> 2024_data.txt
▼ Hint
- Use
os.listdir(directory)to get a list of all filenames in the target folder. - Filter the list using
filename.endswith(".txt")to target only text files. - Build the full old and new paths using
os.path.join(directory, filename)before callingos.rename().
▼ Solution & Explanation
Explanation:
os.listdir(directory): Returns a list of all entry names (files and subdirectories) inside the specified directory. Using"."targets the current working directory.filename.endswith(".txt"): Filters the directory listing so that only files with a.txtextension are processed, leaving other file types untouched.os.path.join(directory, filename): Constructs a proper file path by joining the directory and filename with the correct separator for the operating system, making the code portable across Windows and Unix systems.prefix + filename: Concatenates the prefix string directly onto the original filename to form the new name, e.g.,"notes.txt"becomes"2024_notes.txt".
Exercise 27: Delete a File from Disk
Problem Statement: Write a Python program to delete a specified file from disk, with a check to confirm the file exists before attempting deletion.
Purpose: This exercise introduces safe file deletion practices using the os module – an important skill for cleanup scripts, temporary file management, and automated maintenance tools.
Given Input: An existing file named temp.txt on disk.
Expected Output: temp.txt has been deleted.
Refer: Delete Files and Directories in Python
▼ Hint
- Use
os.path.exists(filename)to check whether the file is present before trying to delete it. - Use
os.remove(filename)to permanently delete the file from disk. - Handle the case where the file does not exist by printing an informative message in the
elsebranch.
▼ Solution & Explanation
Explanation:
os.path.exists(filename): ReturnsTrueif the given path points to an existing file or directory, andFalseotherwise. This guards against aFileNotFoundErrorwhen the file is missing.os.remove(filename): Permanently deletes the specified file from disk. Unlike moving to a recycle bin, this operation cannot be undone through normal means, so the existence check beforehand is good practice.elsebranch: Provides a clear, user-friendly message when the file is not found, making the program more robust and easier to debug in automated environments.- Note:
os.remove()only works on files. To delete an empty directory, useos.rmdir(). For a non-empty directory, useshutil.rmtree().
Exercise 28: Merge Two Files into One
Problem Statement: Write a Python program to read the contents of two separate text files and write their combined content into a single new file.
Purpose: This exercise practises reading from multiple sources and writing to a single destination – a pattern used in report generation, log aggregation, and document assembly pipelines.
Given Input: Two files – file1.txt containing Hello from file 1. and file2.txt containing Hello from file 2.
Expected Output: A new file merged.txt containing both lines, confirmed by printing Files merged into merged.txt
▼ Hint
- Store the names of both source files in a list so you can loop over them.
- Open the output file once in write mode (
"w") and keep it open while you loop through each source file. - Use
outfile.write(infile.read())inside the loop to copy each file’s content into the merged output.
▼ Solution & Explanation
Explanation:
input_files = ["file1.txt", "file2.txt"]: Stores the source filenames in a list, making it easy to extend the program to merge more files by simply adding entries to the list.open(output_file, "w"): Opens the merged output file once in write mode before the loop starts, so all content is written to the same file handle in a single session.outfile.write(infile.read()): Reads the entire content of each source file and writes it directly into the output file, appending one file’s content after the other.outfile.write("\n"): Inserts a newline between the contents of each file so that the last line of one file does not run directly into the first line of the next.
Exercise 29: Reverse Line Order and Save to New File
Problem Statement: Write a Python program to read all lines from a text file, reverse their order, and save the result to a new file.
Purpose: This exercise practises reading lines into a list, applying list reversal, and writing back to a file – skills applicable in log analysis, data reordering, and text transformation utilities.
Given Input: A file original.txt with three lines: Line 1, Line 2, Line 3.
Expected Output:
Line 3 Line 2 Line 1
▼ Hint
- Use
f.readlines()to read all lines into a list at once. - Reverse the list using the
[::-1]slice or the.reverse()method. - Write the reversed list to a new file using
outfile.writelines().
▼ Solution & Explanation
Explanation:
f.readlines(): Reads every line from the file into a Python list, with each element being one line including its trailing newline character. This loads the full structure needed for reordering.lines[::-1]: Creates a new list that is a reversed copy of the original using Python’s slice notation. The-1step iterates from the last element to the first without modifying the original list.f.writelines(reversed_lines): Writes a list of strings to the file in one call. Unlikewrite(), it does not add any separators between items, so the existing newline characters within each element handle the line breaks correctly.
Exercise 30: List All Files in Directory and Save
Problem Statement: Write a Python program to list all files (not subdirectories) in a given directory and save their names to a text file.
Purpose: This exercise combines directory traversal with file writing – a practical pattern used in file inventory scripts, backup tools, and project documentation generators.
Given Input: A directory my_folder containing notes.txt, data.csv, and report.pdf.
Expected Output: A file file_list.txt containing one filename per line, confirmed by printing File list saved to file_list.txt
Refer: Python List Files in a Directory
▼ Hint
- Use
os.listdir(directory)to get all entries in the folder. - Use
os.path.isfile(os.path.join(directory, entry))to filter out subdirectories and keep only files. - Write each filename on its own line using
outfile.write(name + "\n")inside a loop.
▼ Solution & Explanation
Explanation:
os.listdir(directory): Returns a list of all entries in the specified directory, including both files and subdirectories. The order of entries is not guaranteed and varies by operating system.os.path.join(directory, entry): Builds the full path for each entry by joining the directory path and the entry name, which is required foros.path.isfile()to work correctly regardless of the current working directory.os.path.isfile(full_path): ReturnsTrueonly for regular files, excluding subdirectories, symbolic links to directories, and other non-file entries from the output.outfile.write(entry + "\n"): Writes just the filename (not the full path) to the output file, with a newline after each entry so every name appears on its own line.
Exercise 31: Read and Write Binary Image File
Problem Statement: Write a Python program to read a binary image file and write its contents to a new file, producing an exact duplicate of the original image.
Purpose: This exercise deepens your understanding of binary file I/O beyond simple text files, illustrating how Python can handle any file format – images, audio, video, or executables – as a stream of raw bytes.
Given Input: An existing image file photo.jpg on disk.
Expected Output: A new file photo_copy.jpg created on disk, confirmed by printing Image copied to photo_copy.jpg
▼ Hint
- Open the source image in binary read mode using
"rb"and the destination in binary write mode using"wb". - Read the full content with
.read()and write it with.write(). - For large images, consider reading in chunks (e.g.,
4096bytes at a time) inside awhileloop to avoid loading the entire file into memory at once.
▼ Solution & Explanation
Explanation:
"rb"and"wb": Thebflag opens the file in binary mode, instructing Python to read and write raw bytes without any newline translation or character encoding. This is essential for non-text file formats like JPEG images.src.read(chunk_size): Reads up to4096bytes at a time from the source file rather than loading the entire file into memory. This approach keeps memory usage low and works well even for very large files.if not chunk: break: Whenread()reaches the end of the file, it returns an emptybytesobject (b""), which is falsy. This condition exits the loop cleanly once all data has been copied.dst.write(chunk): Writes each chunk of bytes directly to the destination file, building the copy incrementally until the entire source has been transferred.
Exercise 32: Extract and Sort Unique Words from File
Problem Statement: Write a Python program to read a text file, extract all unique words, sort them alphabetically, and print the result.
Purpose: This exercise practises file reading, string normalisation, set operations for deduplication, and sorting – key techniques in vocabulary building, text indexing, and content analysis tasks.
Given Input: A file paragraph.txt containing: the cat sat on the mat the cat
Expected Output:
cat mat on sat the
▼ Hint
- Read the file and use
.lower()and.split()to produce a normalised list of words. - Pass the list into a
set()to automatically remove duplicate words. - Use
sorted()on the set to get an alphabetically ordered sequence to loop over and print.
▼ Solution & Explanation
Explanation:
content.lower(): Converts all text to lowercase before processing so thatTheandtheare treated as the same word during deduplication.str.maketrans("", "", string.punctuation): Creates a translation table that maps every punctuation character to nothing, effectively stripping commas, periods, apostrophes, and other symbols from the text before splitting.set(words): Converts the word list to a set, which automatically discards duplicate entries since sets only store unique values.sorted(set(words)): Returns a new list of the unique words arranged in ascending alphabetical order. Sorting a set directly is not stable, so wrapping it insorted()guarantees a consistent order.
Exercise 33: Filter Log File Lines Containing ERROR Keyword
Problem Statement: Write a Python program to read a log file line by line and print (or save) only the lines that contain the keyword ERROR.
Purpose: This exercise simulates a real-world log analysis task, practising line-by-line file reading, keyword filtering, and conditional output – skills central to system monitoring, debugging tools, and DevOps automation.
Given Input: A file app.log with mixed log levels, where some lines contain ERROR.
Expected Output:
2024-01-01 10:02:05 ERROR Disk quota exceeded 2024-01-01 10:07:45 ERROR Connection timeout
▼ Hint
- Read the log file line by line using a
forloop over the file object. - Use the
inoperator to check if the string"ERROR"appears in each line. - Use
.strip()when printing to remove trailing newline characters from each matching line.
▼ Solution & Explanation
Explanation:
for line in f: Iterates over the file object one line at a time. This approach is memory-efficient because Python reads each line on demand rather than loading the entire file into memory, which is important for large log files.if keyword in line: Uses Python’sinmembership operator to check whether the substring"ERROR"exists anywhere within the current line. This is case-sensitive, so"error"or"Error"would not match.line.strip(): Removes the trailing newline character (\n) thatreadlines-style iteration preserves, so the printed output does not have blank lines between each result.- Extension: To save matching lines to a file instead of printing them, open an output file alongside the log file and use
outfile.write(line)for each match – no.strip()needed in that case since the newline helps separate entries.
Exercise 34: Split Large File into Smaller 10-Line Files
Problem Statement: Write a Python program to read a large text file and split it into smaller files, each containing at most 10 lines, saving them as part_1.txt, part_2.txt, and so on.
Purpose: This exercise practises chunked file processing and dynamic file creation – techniques used in data partitioning, batch upload preparation, and breaking large datasets into manageable pieces for parallel processing.
Given Input: A file large_file.txt containing 25 lines of text.
Expected Output:
Created: part_1.txt (10 lines) Created: part_2.txt (10 lines) Created: part_3.txt (5 lines)
▼ Hint
- Read all lines into a list using
f.readlines(). - Use a
range(0, total_lines, 10)loop to step through the list in chunks of 10, using list slicing to extract each chunk. - Track the part number with a counter and use an f-string to build each output filename dynamically (e.g.,
f"part_{part_num}.txt").
▼ Solution & Explanation
Explanation:
f.readlines(): Reads all lines from the large file into a list at once. Each element is one line including its newline character, preserving the structure needed for writing to part files.range(0, total_lines, chunk_size): Generates starting indices at intervals of 10 (e.g., 0, 10, 20), allowing the loop to step through the full line list in non-overlapping chunks of the specified size.lines[start:start + chunk_size]: Slices exactly 10 lines from the full list for each iteration. When fewer than 10 lines remain (such as the final chunk), Python’s slice safely returns only the remaining lines without raising an error.enumerate(..., start=1): Pairs each chunk’s starting index with a 1-based part number, which is used to build descriptive output filenames likepart_1.txt,part_2.txt, and so on.out.writelines(chunk): Writes the list of lines for each chunk directly to the part file. Since each line already contains its trailing newline fromreadlines(), no manual\nis needed.
