Class 12 : Data File Handling

#### Class 12 File Handling Questions

File Handling Set 1
File Handling Set 2
File Handling Set 3
File Handling Set 4
File Handling Set 5
File Handling Set 6
File Handling Set 7

# Class XII: Python Data File Handling 7

Question:1
write a (python script) function named read_words() to read the contents of the file “abc.txt” word by word and display the contents.
Sol:

Method:1

```def read_words():
with open("file1.txt") as f:
while True:
if not d:
break
for word in d.split():
#for word  in line.split():
print(word)
#function calling

Method:2

```def read_words():
with open("file1.txt") as f:
for line in f:
for word  in line.split():
print(word)
#function calling

Question:2
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total words in the file.
Sol:

Method 1

```def read_words():
c=0
with open("file1.txt") as f:
while True:
if not d:
break
for word in d.split():
#for word  in line.split():
print(word)
c=c+1
print('no of words=',c)
#function calling

Method 2

```def count_words():
w=0
with open("file1.txt") as f:
for line in f:
for word  in line.split():
print(word)
w=w+1
print("total words ",w)
#function calling
count_words()```

Question:3
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total number of words starting with “a” or “A” in the file.
Sol:

```def count_words():
w=0
with open("abc.txt") as f:
for line in f:
for word  in line.split():
if(word[0]=="a" or word[0]=="A"):
print(word)
w=w+1
print("total words starting with 'a' are ",w)
#function calling
count_words()```

Question:4
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total number of words starting with tarting with vowels “a”,”e”,”i”,”o”,”u” or “A” ,”E”,”I”,”O”,”U”
Sol:

```def count_words():
w=0
vowels="aeiouAEIOU"
with open("abc.txt") as f:
for line in f:
for word  in line.split():
if(word[0] in vowels):
print(word)
w=w+1
print("total words starting with vowels are ",w)
#function calling
count_words()```

Important Pages