Questions on Text Files in Python

Theory Questions on text files in Python

What does the read() function do in Python?

It reads the entire content of a file as a single string.

How do I use read() to read only part of a file?

You can pass a number as an argument to read a specific number of bytes:

python
file.read(100)  # Reads first 100 characters

What happens if I call read() multiple times?

It continues reading from where the last read ended, unless you reset the file pointer.

How do I reset the file pointer after using read()?

Use file.seek(0) to move the pointer back to the beginning.

Can I use read() with binary files?

Yes, but you must open the file in binary mode:

python
open("file.bin", "rb").read()

What’s the difference between read() and readlines()?

read() returns a single string; readlines() returns a list of lines.

Does read() automatically close the file?

No. You should use a with block to ensure the file is closed properly.

Can I use read() on large files?

It’s not recommended, as it loads the entire file into memory. Use readline() or iterate line by line instead.

What does read(0) return?

It returns an empty string ''.

How do I check if the file is readable before using read()?

Use file.readable() which returns True or False.

Programming Questions text files in Python

Here are 20 Python questions similar to your original request (reading a text file and performing word-based analysis), each with a solution. These are great for practicing file handling, string manipulation, and basic logic:

  1. Count total number of words in a text file
def count_words(file_path):
    with open(file_path, 'r') as f:
        return len(f.read().split())
  1. Count number of lines in a text file
def count_lines(file_path):
    with open(file_path, 'r') as f:
        return len(f.readlines())
  1. Count number of characters in a text file
def count_characters(file_path):
    with open(file_path, 'r') as f:
        return len(f.read())
  1. Count words starting with a vowel
def count_vowel_words(file_path):
    vowels = 'aeiouAEIOU'
    with open(file_path, 'r') as f:
        return sum(1 for word in f.read().split() if word[0] in vowels)
  1. Count words ending with ‘ing’
def count_ing_words(file_path):
    with open(file_path, 'r') as f:
        return sum(1 for word in f.read().split() if word.endswith('ing'))
  1. Find the longest word in a text file
def longest_word(file_path):
    with open(file_path, 'r') as f:
        words = f.read().split()
        return max(words, key=len)
  1. Find the shortest word in a text file
def shortest_word(file_path):
    with open(file_path, 'r') as f:
        words = f.read().split()
        return min(words, key=len)
  1. Count number of unique words
def count_unique_words(file_path):
    with open(file_path, 'r') as f:
        return len(set(f.read().split()))
  1. List all words longer than 6 characters
def long_words(file_path):
    with open(file_path, 'r') as f:
        return [word for word in f.read().split() if len(word) > 6]
  1. Count frequency of each word
from collections import Counter
def word_frequency(file_path):
    with open(file_path, 'r') as f:
        return Counter(f.read().split())
  1. Count number of blank lines
def count_blank_lines(file_path):
    with open(file_path, 'r') as f:
        return sum(1 for line in f if line.strip() == '')
  1. Replace all occurrences of a word
def replace_word(file_path, old, new):
    with open(file_path, 'r') as f:
        text = f.read().replace(old, new)
    with open(file_path, 'w') as f:
        f.write(text)
  1. Check if a word exists in the file
def word_exists(file_path, word):
    with open(file_path, 'r') as f:
        return word in f.read().split()
  1. Extract all numeric values from the file
def extract_numbers(file_path):
    with open(file_path, 'r') as f:
        return [word for word in f.read().split() if word.isdigit()]
  1. Count number of sentences (assuming ‘.’ ends a sentence)
def count_sentences(file_path):
    with open(file_path, 'r') as f:
        return f.read().count('.')
  1. Convert all text to uppercase
def convert_upper(file_path):
    with open(file_path, 'r') as f:
        text = f.read().upper()
    with open(file_path, 'w') as f:
        f.write(text)
  1. Find all palindromic words
def find_palindromes(file_path):
    with open(file_path, 'r') as f:
        return [word for word in f.read().split() if word == word[::-1] and len(word) > 1]
  1. Count words with only alphabetic characters
def count_alpha_words(file_path):
    with open(file_path, 'r') as f:
        return sum(1 for word in f.read().split() if word.isalpha())
  1. Find average word length
def average_word_length(file_path):
    with open(file_path, 'r') as f:
        words = f.read().split()
        return sum(len(word) for word in words) / len(words)
  1. Print all words in reverse order
def reverse_words(file_path):
    with open(file_path, 'r') as f:
        return [word[::-1] for word in f.read().split()]

 

 

 
error: Content is protected !!