Interview

10 File Handling Interview Questions and Answers

Prepare for your next interview with our comprehensive guide on file handling, covering essential concepts and practical skills.

File handling is a fundamental aspect of programming that involves creating, reading, writing, and managing files. Mastery of file handling is crucial for tasks such as data storage, configuration management, and logging. Understanding how to efficiently manipulate files can significantly enhance the performance and reliability of software applications.

This article offers a curated selection of file handling interview questions designed to test and improve your knowledge in this area. By working through these questions, you will gain a deeper understanding of file operations, preparing you to tackle real-world challenges and impress potential employers with your technical proficiency.

File Handling Interview Questions and Answers

1. Describe the purpose of the ‘with’ statement in Python file handling.

The ‘with’ statement in Python is used to wrap the execution of a block of code, ensuring that resources like files are properly managed. In file handling, it automatically closes the file after the block is executed, even if an exception occurs, making the code concise and reducing file-related errors.

Example:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

In this example, the ‘with’ statement ensures that ‘example.txt’ is closed after reading, regardless of exceptions.

2. Write a function to copy the contents of one file to another in Python.

To copy the contents of one file to another, open the source file in read mode and the destination file in write mode, then transfer the contents.

Example:

def copy_file_contents(source_file, destination_file):
    with open(source_file, 'r') as src:
        with open(destination_file, 'w') as dest:
            dest.write(src.read())

# Usage
copy_file_contents('source.txt', 'destination.txt')

3. Write a Python function to count the number of words in a text file.

To count the number of words in a text file, read the file’s contents and split the text into words.

Example:

def count_words_in_file(filename):
    with open(filename, 'r') as file:
        contents = file.read()
        words = contents.split()
        return len(words)

# Example usage
word_count = count_words_in_file('example.txt')
print(f'The number of words in the file is: {word_count}')

4. Write a Python script to find and replace a specific word in a text file.

To find and replace a specific word in a text file, read the file, perform the replacement, and write the modified content back.

Example:

def find_and_replace(file_path, old_word, new_word):
    with open(file_path, 'r') as file:
        content = file.read()
    
    content = content.replace(old_word, new_word)
    
    with open(file_path, 'w') as file:
        file.write(content)

# Example usage
find_and_replace('example.txt', 'old_word', 'new_word')

5. Write a Python function to merge multiple text files into a single file.

To merge multiple text files into a single file, read each file’s contents and write them into a new file.

Example:

import os

def merge_files(output_file, *input_files):
    with open(output_file, 'w') as outfile:
        for fname in input_files:
            if os.path.isfile(fname):
                with open(fname) as infile:
                    outfile.write(infile.read())
                    outfile.write("\n")  # Optional: Add a newline between files

# Example usage
merge_files('merged.txt', 'file1.txt', 'file2.txt', 'file3.txt')

6. How would you use Python to read and write compressed files (e.g., .zip or .gz)?

Python provides libraries like zipfile for .zip files and gzip for .gz files to handle compressed files.

For .zip files:

import zipfile

# Writing to a zip file
with zipfile.ZipFile('example.zip', 'w') as zipf:
    zipf.write('file_to_compress.txt')

# Reading from a zip file
with zipfile.ZipFile('example.zip', 'r') as zipf:
    zipf.extractall('extracted_files')

For .gz files:

import gzip

# Writing to a gzip file
with gzip.open('example.txt.gz', 'wb') as gzfile:
    gzfile.write(b'This is some content to compress')

# Reading from a gzip file
with gzip.open('example.txt.gz', 'rb') as gzfile:
    content = gzfile.read()
    print(content)

7. Write a Python function to read specific lines from a file.

To read specific lines from a file, open the file and extract the desired lines.

Example:

def read_specific_lines(filename, lines):
    try:
        with open(filename, 'r') as file:
            content = file.readlines()
            return [content[i - 1] for i in lines if 0 < i <= len(content)]
    except FileNotFoundError:
        print(f"The file {filename} does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage
lines_to_read = [1, 3, 5]
print(read_specific_lines('example.txt', lines_to_read))

8. Write a Python function to write JSON data to a file.

To write JSON data to a file, use the json module’s dump method.

Example:

import json

def write_json_to_file(data, filename):
    with open(filename, 'w') as file:
        json.dump(data, file, indent=4)

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

write_json_to_file(data, 'data.json')

9. Write a Python function to read a CSV file and print its contents.

To read a CSV file and print its contents, use the csv module.

Example:

import csv

def read_csv_file(file_path):
    with open(file_path, mode='r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            print(row)

# Example usage
read_csv_file('example.csv')

10. Write a Python function to create and use a temporary file.

Temporary files can be created using the tempfile module, which automatically handles cleanup.

Example:

import tempfile

def create_temp_file():
    with tempfile.NamedTemporaryFile(delete=True) as temp_file:
        temp_file.write(b'Hello, world!')
        temp_file.seek(0)
        print(temp_file.read())

create_temp_file()
Previous

10 Imperva Interview Questions and Answers

Back to Interview
Next

10 Repository Pattern Interview Questions and Answers