PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python File Handling Exercises

Python File Handling Exercises

Updated on: April 30, 2025 | 4 Comments

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:

  • Python File Handling
  • Read File in Python
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
try:
    with open("sample.txt", 'r') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("Error: 'sample.txt' not found.")Code language: Python (python)

Explanation:

  • with open("sample.txt", 'r') as file: opens the file named “sample.txt” in read mode. The with 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 the content 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
try:
    with open("sample.txt", 'r') as file:
        for line in file:
            print(line, end='') # The 'end=''' prevents extra newline characters
except FileNotFoundError:
    print("Error: 'sample.txt' not found.")Code language: Python (python)

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 use end='' 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 Hint
  • Use for loop with range() function as a counter to keep track of the number of lines read. Once you’ve reached the desired number of lines, you can stop the reading process.
  • In each iteration of a loop use a readline() function to read single line from file
Show Solution
try:
    with open("sample.txt", 'r') as file:
        for i in range(5):
          print(file.readline().strip())
except FileNotFoundError:
    print("Error: 'sample.txt' not found.")Code language: Python (python)

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:

  • Python regex find all matches
  • Python regex split
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
import re

def count_words(filename):
    try:
        with open(filename, 'r') as file:
            content = file.read().lower()
            words = re.findall(r'\b\w+\b', content) # Use regex to find whole words
            return len(words)
    except FileNotFoundError:
        return f"Error: '{filename}' not found."

# Example usage:
word_count = count_words("sample.txt")
print(f"Total words in 'sample.txt': {word_count}")Code language: Python (python)

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 expression r'\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. The try-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
# Solution:
def count_characters(filename):
    try:
        with open(filename, 'r') as file:
            content = file.read()
            return len(content)
    except FileNotFoundError:
        return f"Error: '{filename}' not found."

# Example usage:
char_count = count_characters("sample.txt")
print(f"Total characters in 'sample.txt': {char_count}")Code language: Python (python)

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 the content 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
def count_specific_word(filename, word):
    try:
        with open(filename, 'r') as file:
            content = file.read().lower()
            words = content.split()
            count = 0
            for w in words:
                # Remove punctuation to ensure accurate matching
                cleaned_word = w.strip('.,!?"\'()[]{};:')
                if cleaned_word == word.lower():
                    count += 1
            return count
    except FileNotFoundError:
        return f"Error: '{filename}' not found."

# Example usage:
filename = "sample.txt"
word_to_count = "the"
occurrences = count_specific_word(filename, word_to_count)
print(f"The word '{word_to_count}' appears {occurrences} times in '{filename}'.")Code language: Python (python)

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 the words 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
filename = "output.txt"
text_to_write = "Hello, PYnative!"

try:
    with open(filename, 'w') as file:
        file.write(text_to_write)
    print(f"Successfully wrote '{text_to_write}' to '{filename}'.")
except Exception as e:
    print(f"An error occurred: {e}")Code language: Python (python)

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
filename = "output.txt"
text_to_append = "This is an appended line."

try:
    with open(filename, 'a') as file:
        file.write("\n" + text_to_append) # Adding a newline character for better readability
    print(f"Successfully appended '{text_to_append}' to '{filename}'.")
except FileNotFoundError:
    print(f"Error: '{filename}' not found.")
except Exception as e:
    print(f"An error occurred: {e}")Code language: Python (python)

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
def copy_file(source_filename, destination_filename):
    try:
        with open(source_filename, 'r') as source_file:
            content = source_file.read()
        with open(destination_filename, 'w') as destination_file:
            destination_file.write(content)
        print(f"Successfully copied '{source_filename}' to '{destination_filename}'.")
    except FileNotFoundError:
        print(f"Error: Source file '{source_filename}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage:
source_file = "sample.txt"
destination_file = "copied_sample.txt"
copy_file(source_file, destination_file)Code language: Python (python)

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
# Solution:
def copy_binary_file(source_filename, destination_filename):
    try:
        with open(source_filename, 'rb') as source_file:
            binary_content = source_file.read()
        with open(destination_filename, 'wb') as destination_file:
            destination_file.write(binary_content)
        print(f"Successfully copied binary file '{source_filename}' to '{destination_filename}'.")
    except FileNotFoundError:
        print(f"Error: Source binary file '{source_filename}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage:
source_binary_file = "input.bin" # Make sure this binary file exists
destination_binary_file = "output.bin"
copy_binary_file(source_binary_file, destination_binary_file)Code language: Python (python)

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.

import os

def check_file_exists(filename):
    return os.path.exists(filename)

# Example usage:
filename = "sample.txt"
exists = check_file_exists(filename)
print(f"Does '{filename}' exist? {exists}")Code language: Python (python)

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.

import os

def get_file_size(filename):
    try:
        size_in_bytes = os.path.getsize(filename)
        return size_in_bytes
    except FileNotFoundError:
        return f"Error: '{filename}' not found."

# Example usage:
filename = "sample.txt"
size = get_file_size(filename)
print(f"The size of '{filename}' is: {size} bytes.")Code language: Python (python)

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.

import os

def rename_file(old_filename, new_filename):
    if not os.path.exists(old_filename):
        return f"Error: File '{old_filename}' not found."
    try:
        os.rename(old_filename, new_filename)
        return f"Successfully renamed '{old_filename}' to '{new_filename}'."
    except Exception as e:
        return f"An error occurred while renaming: {e}"

# Example usage:
old_name = "old_file.txt"
new_name = "new_file.txt"Code language: Python (python)

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.

import os

def delete_file(filename):
    if not os.path.exists(filename):
        return f"Error: File '{filename}' not found."
    try:
        os.remove(filename)
        return f"Successfully deleted '{filename}'."
    except Exception as e:
        return f"An error occurred while deleting: {e}"

# Example usage:
file_to_delete = "temp_file.txt"

# Create a dummy file to test deletion
with open(file_to_delete, 'w') as f:
    f.write("This file will be deleted.")

result = delete_file(file_to_delete)
print(result)Code language: Python (python)

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
def replace_in_file(source_filename, destination_filename, old_word, new_word):
    try:
        with open(source_filename, 'r') as source_file:
            content = source_file.read()
        modified_content = content.replace(old_word, new_word)
        with open(destination_filename, 'w') as destination_file:
            destination_file.write(modified_content)
        return f"Successfully replaced '{old_word}' with '{new_word}' in '{source_filename}' and saved to '{destination_filename}'."
    except FileNotFoundError:
        return f"Error: Source file '{source_filename}' not found."
    except Exception as e:
        return f"An error occurred: {e}"

# Example usage:
source_file = "sample.txt"
destination_file = "replaced_file.txt"
word_to_replace = "old"
replacement_word = "new"

# Create a dummy file to test replacement
with open(source_file, 'w') as f:
    f.write("This is an old file with some old content.")

result = replace_in_file(source_file, destination_file, word_to_replace, replacement_word)
print(result)Code language: Python (python)

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.

Filed Under: Python, Python Exercises, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises Python File Handling

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Exercises Python File Handling
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement