Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Text_File_Questions_Class12

The document provides a series of Python programming exercises focused on basic file operations, searching, counting, and file modification. It includes code snippets for creating, reading, counting, and modifying text files. Key tasks include counting words, displaying specific lines, copying file contents, and reversing line order in a file.

Uploaded by

menonsujithg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Text_File_Questions_Class12

The document provides a series of Python programming exercises focused on basic file operations, searching, counting, and file modification. It includes code snippets for creating, reading, counting, and modifying text files. Key tasks include counting words, displaying specific lines, copying file contents, and reversing line order in a file.

Uploaded by

menonsujithg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Important Text File Questions - Class 12 Computer Science

1. Basic File Operations

Q1. Write a Python program to create a text file and write some lines into it.

with open("sample.txt", "w") as f:

f.write("Hello, this is a test file.\n")

f.write("This is the second line.")

Q2. Write a program to read a text file line by line and display each line.

with open("sample.txt", "r") as f:

for line in f:

print(line, end="")

Q3. Read a text file and count the total number of characters, words, and lines.

with open("sample.txt", "r") as f:

lines = f.readlines()

num_lines = len(lines)

num_words = sum(len(line.split()) for line in lines)

num_chars = sum(len(line) for line in lines)

print("Lines:", num_lines, "Words:", num_words, "Characters:", num_chars)

2. Searching and Counting

Q1. Count the number of times a specific word appears in a text file.

word_to_count = "test"

count = 0

with open("sample.txt", "r") as f:

for line in f:

count += line.lower().split().count(word_to_count.lower())

print("Count:", count)

Q2. Display all lines in a file that contain a specific word.


word = "test"

with open("sample.txt", "r") as f:

for line in f:

if word.lower() in line.lower():

print(line, end="")

3. File Modification

Q1. Copy contents of one file to another.

with open("sample.txt", "r") as f1, open("copy.txt", "w") as f2:

f2.write(f1.read())

Q2. Read a text file and write its content in reverse order (line-wise).

with open("sample.txt", "r") as f:

lines = f.readlines()

with open("reversed.txt", "w") as f:

for line in reversed(lines):

f.write(line)

You might also like