This article serves as a practical exercise guide, designed to solidify your understanding of Python’s file handling capabilities through a series of hands-on challenges.
This Python File Handling exercise contains 15 different coding questions and challenges to gain proficiency in essential operations such as file reading, file writing, renaming a file, copying file, deleting a file, and various file handling task such as checking file existence, managing file properties, content filtering, and replacement.
Also, See:
- Python Exercises: A set of 17 topic specific exercises
- Python Quizzes: Solve quizzes to test your knowledge of fundamental concepts.
- Python File Handling: Master Python File Handling to solve these exercises
- Hint and code solutions are provided for all questions and tested on Python 3.
- Tips and essential learning resources accompany each question. These will assist you in solving the exercise.
Let us know if you have any alternative solutions. It will help other developers.
Table of contents
- Exercise 1: Read a File
- Exercise 2: Read File Line by Line
- Exercise 3: Read Specific Lines From a File
- Exercise 4: Count Words From a File
- Exercise 5: Count Total Number of Characters in File
- Exercise 6: Count Specific Word From a File
- Exercise 7: Write To a File
- Exercise 8: Append To a File
- Exercise 9: Copy a File
- Exercise 10: Read and Write Binary
- Exercise 11: File Existence Check
- Exercise 12: Get File Size
- Exercise 13: Rename a File
- Exercise 14: Delete a File
- Exercise 15: Replace In File
- Next Steps
Exercise 1: Read a File
Write a Python program to read the entire contents of a text file named “sample.txt” and print it to the console.
Refer:
Show Hint
You’ll need to open the file in read mode ('r'
) and then use a read()
method to read the entire content at once.
Show Solution
Explanation:
with open("sample.txt", 'r') as file:
opens the file named “sample.txt” in read mode. Thewith
statement ensures the file is automatically closed even if errors occur.content = file.read()
method reads the entire content of the file as a single string and stores it in thecontent
variable.- At last the
print(content)
functions then displays the content on the console.
Exercise 2: Read File Line by Line
Write a Python program to read the text file named “sample.txt” line by line and print each line.
Refer: Read File in Python
Show Hint
- Don’t load the entire file into memory at once.
- Use loop to iterate through file object in Python.
- In each iteration of the loop you can print single line from the file
Show Solution
Explanation:
- Similar to the previous example, we open the file in read mode using
with open(...)
. - The
for line in file:
loop iterates over each line in the file. - Each
line
variable will contain a single line from the file, including the newline character at the end. print(line, end='')
prints each line. We useend=''
to prevent an extra newline from being printed after each line, as the lines themselves already contain a newline character.
Exercise 3: Read Specific Lines From a File
Write a Python program to read only the first 5 lines of “sample.txt”.
Refer: Read File in Python
Show Solution
Exercise 4: Count Words From a File
Create a function that takes a filename as input and returns the total number of words in that file.
Refer:
Show Hint
You’ll need to read the file content, split it into words, and then count the number of resulting elements. Remember to handle potential punctuation.
Show Solution
Explanation:
- We import the
re
module for regular expression operations. - The
count_words
function takes the filename as input. It opens the file in read mode.content = file.read().lower()
reads the entire content and converts it to lowercase to ensure consistent word counting. words = re.findall(r'\b\w+\b', content)
uses a regular expressionr'\b\w+\b'
to find all whole words.\b
matches word boundaries, and\w+
matches one or more word characters (letters, numbers, and underscore).return len(words)
returns the total number of words found. Thetry-except
block handles the case where the file is not found
Exercise 5: Count Total Number of Characters in File
Write a function that takes a filename as input and returns the total number of characters in that file (including spaces and newlines).
Show Hint
Read the entire file content into string and then find the length of the string.
Show Solution
Explanation:
- The
count_characters
function takes the filename as input. - It opens the file in read mode.
content = file.read()
reads the entire content of the file as a single string. return len(content)
returns the length of thecontent
string, which represents the total number of characters (including spaces and newline characters).
Exercise 6: Count Specific Word From a File
Write a program to count the occurrences of a specific word (e.g., “hello”) in a given file.
Refer: Python Search for a String in Text Files
Show Hint
Open the file, read its content, To count a specific word, you should probably convert the entire text to a consistent case (either lowercase or uppercase) to avoid missing matches due to capitalization. Then, split the text into individual words and iterate through them to check for your target word.
Show Solution
Explanation:
- The
count_specific_word
function opens the file in read mode and reads the entire content, converting it to lowercase - Using
.lower()
.content.split()
splits the text into a list of words using whitespace as the delimiter. - The code iterates through each
w
in thewords
list.w.strip('.,!?"\'()[]{};:')
removes common punctuation marks from the beginning and end of each word to ensure accurate matching.
Exercise 7: Write To a File
Write a Python program to create a new file named “output.txt” and write the string “Hello, PYnative!” into it.
Refer: Write to File Python
Show Hint
Open a new file in write mode ('w'
) and use the write method.
Show Solution
Explanation:
with open(filename, 'w') as file:
opens the file in write mode. If “output.txt” doesn’t exist, it will be created. If it does exist, its contents will be overwritten.- The
with
statement ensures the file is automatically closed.file.write(text_to_write)
writes the specified string to the file.
Exercise 8: Append To a File
Modify the previous program to append the string “This is an appended line.” to the end of “output.txt”.
Refer: Append to a File
Show Hint
You need to open file in a different mode that allows you to add content to the end. Use a
mode.
Show Solution
Explanation:
with open(filename, 'a') as file:
opens the file in append mode ('a'
). If “output.txt” doesn’t exist, it will be created. If it does exist, new content will be added at the end.file.write("\n" + text_to_append)
writes the string to the file.
Exercise 9: Copy a File
Write a program that takes two filenames as input (source and destination) and copies the content of the source file to the destination file.
Refer: Copy Files and Directories in Python
Show Hint
Open the source file in read mode, read its content, then open the destination file in write mode and write the content.
Show Solution
Exercise 10: Read and Write Binary
Write a program to read data from a binary file (“input.bin”) and write it to another binary file (“output.bin”).
Show Hint
- You need to open them in binary modes (
'rb'
for read binary and'wb'
for write binary). - Reading from a binary file will give you bytes objects, and you should write bytes objects to a binary file.
- You can read the entire content of the source binary file and then write that directly to the destination binary file.
Show Solution
Explanation:
- The
copy_binary_file
function opens the source file in read binary mode ('rb'
). binary_content = source_file.read()
reads the entire content of the binary file as a bytes object.- Next,
with open(destination_filename, 'wb') as destination_file:
opens the destination file in write binary mode ('wb'
). destination_file.write(binary_content)
writes the bytes read from the source file to the destination file.
Exercise 11: File Existence Check
Write a function that takes a filename as input and returns True
if the file exists and False
otherwise.
Refer: Python Check If File Exists
Show Hint
You need to use a os module that provides functions for interacting with the operating system. This module has a function to check if a file path points to an existing file.
Show Solution
The os.path.exists(filename)
checks if the file specified by filename
exists. It returns True
if the file or directory exists, and False
otherwise.
Exercise 12: Get File Size
Write a program to get the size of a file (in bytes).
Refer: Python Check File Size
Show Hint
Similar to checking for existence, you’ll need to use the os
module. There’s a function to get file-related information, and within that information, you can find the size of the file.
Show Solution
The os.path.getsize(filename)
returns the size of the file specified by filename
in bytes.
Exercise 13: Rename a File
Write a program that takes an old filename and a new filename as input and renames the file. Handle potential errors if the old file doesn’t exist.
Refer: Rename Files in Python
Show Hint
The os
module provides a function specifically designed for renaming files. You’ll need to provide both the old and the new filenames to this function.
Show Solution
The os.rename(old_filename, new_filename)
renames the file from old_filename
to new_filename
.
Exercise 14: Delete a File
Write a program that takes a filename as input and deletes the file. Handle potential errors if the file doesn’t exist.
Refer: Delete Files and Directories in Python
Show Hint
The os
module also has a function for removing files. It’s good practice to check if file exists to prevent errors before deleting it.
Show Solution
The os.remove(filename)
deletes the specified file.
Exercise 15: Replace In File
Write a program that reads a text file, replaces all occurrences of a specific word with another word, and writes the modified content to a new file.
Show Hint
- First, read the entire content of the source file.
- Next, use string
replace()
method to replace all occurrences of the old word with the new word. - Finally, open a new file in write mode and write the modified content to it.
Show Solution
Next Steps
I want to hear from you. What do you think of this exercise? If you have better alternative answers to the above questions, please help others by commenting on this exercise.
Also, we have Topic-specific exercises to cover each topic exercise in detail. Please refer to all Python exercises.
Leave a Reply