PRIP 5.1 Sumita Arora Solutions | Class 12 Computer Science

Here are PRIP 5.1 Sumita Arora Solutions for class 12 Computer Science. To view Sumita Arora solutions for all chapters, visit here.

Consider the file “sarojiniPoem.txt” 
Q.1: Based on above file, answer the following questions:                         
Note:
file content is shown here only for reference
to execute programs sucessfully user need to save file with name “sarojiniPoem.txt” 
Autumn Song

Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,

Of fair and trail and fluttering leaves, 
The wild wind blows in a cloud.

Hark to a voice that is calling,
To my heart in the voice of the wind;
My heart is weary and sad and alone, 
For its dreams like the fluttering leaves have gone,
And why should I stay behind?


Sarojini Naidu

(a) What would be the output of following code:

file = open(“sarojiniPoem.txt”,”r”) 
text = file.readlines() 
file.close()

for line in text:
    print(line, end = ”) 
print()

Answer:

Output:
Autumn Song

Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,
Of fair and trail and fluttering leaves, 
The wild wind blows in a cloud.

Hark to a voice that is calling,
To my heart in the voice of the wind;
My heart is weary and sad and alone, 
For its dreams like the fluttering leaves have gone,
And why should I stay behind?

Sarojini Naidu

(b) Modify the program so that the lines are printed in reverse order.
Answer:

Code:
file = open("sarojiniPoem.txt","r") 
text = file.readlines() 
file.close()

for line in reversed(text):   # use reversed function
    print(line, end = '') 
print()


Output:
Sarojini Naidu
And why should I stay behind?
For its dreams like the fluttering leaves have gone,
My heart is weary and sad and alone, 
To my heart in the voice of the wind;
Hark to a voice that is calling,

The wild wind blows in a cloud.
Of fair and trail and fluttering leaves, 
A golden storm of glittering sheaves,
The sunset hangs on a cloud;
Like a joy on the heart of a sorrow,

Autumn Song


(c) Modify the code so as to output to another file instead of the screen. Let your script overwrite the output file.
Answer:

Code:
file = open("sarojiniPoem.txt","r")  #open file in read mode
text = file.readlines() 
file.close()
f = open("newSarojiniPoem.txt", "w") #open file in write mode
for line in text:                    #write each line to new file    
    f.write(line)     
f.close()


Output:
Output of program can be seen in 'newSarojiniPoem.txt' 
overwrite is the process of replacing old information with new information
hence each time we run program previous information will be changed by new
information.

(d) Change the script of part (c) so that it appends the output to an existing file.
Answer:

Code:
file = open("sarojiniPoem.txt","r")    #open file in read mode
text = file.readlines() 
file.close()
f = open("newSarojiniPoem1.txt", "a") #open file in append mode
for line in text:
    f.write(line)     
f.close()


Output:
Output of program can be seen in 'newSarojiniPoem1.txt' 
to append is to join or add on to the end of something
i.e. after executing program the both old and new information
will appear in 'newSarojiniPoem1.txt' 

(e) Modify the program so that each line is printed with a line number at the beginning.
Answer:

Code:
file = open("sarojiniPoem.txt","r")   #open file in read mode
text = file.readlines() 
file.close()
count=1                               # set counter 
for line in text:
    print("{}. {}".format(count,line), end = '')  #print line
    count+=1                          #increment counter
print()


Output:
1. Autumn Song
2. 
3. Like a joy on the heart of a sorrow,
4. The sunset hangs on a cloud;
5. A golden storm of glittering sheaves,
6. Of fair and trail and fluttering leaves, 
7. The wild wind blows in a cloud.
8. 
9. Hark to a voice that is calling,
10. To my heart in the voice of the wind;
11. My heart is weary and sad and alone, 
12. For its dreams like the fluttering leaves have gone,
13. And why should I stay behind?
14. 
15. Sarojini Naidu
Q.2: Write a program to print following type of statistics for the given file:
16824 lines in the file 
483 empty lines
53.7 average characters per line
65.9 average characters per non-empty line

Answer:

Code:
file = open("sarojiniPoem.txt","r") 
text = file.readlines() 
file.close()
lineCount = 0
empty = 0
character = 0

for line in text:     # iterate over text 
    temp=0
    if(line=="\n"):   # check if line is empty or not 
        lineCount+=1  #increment lineCount
        empty+=1      #increment empty
    else:
        lineCount+=1 #increment lineCount
        wordslist=line.split() #split line to list of words
        for w in wordslist:
            character+=len(w)

print("{} lines in the file ".format(lineCount))
print("{} empty lines ".format(empty))
averageChar = character/(lineCount-empty)
print("{:.2f} average characters per line".format(averageChar))
avgCharNonEmpty = character/(lineCount)
print("{:.2f} average characters per non-empty line ".format(avgCharNonEmpty))


Output:
15 lines in the file 
3 empty lines 
26.42 average characters per line
21.13 average characters per non-empty line
Q.3: Write a program that asks a new user about userid and password and then append it to file “security.txt” provided the given userid does not exist in the file. If it does, then display error message “User id already exists” and prompts the user to re-enter the userid. Also, make sure that the password is at least 8 characters long with at-least a digit and a special character out of “$,@ and%” in it.

Answer:

Code:
def valid_password(password):         # password validation funtion
    if (len(password) >= 8): 
        if(" " not in password):
            if("@" in password or "$" in password or "%" in password):
                return True
    return False

while(True):                        
    userid = input("Enter user id:")   #input userid
    f = open("security.txt", "r+")
    data = f.readlines()
    validusr = True
    validpass = True
    for line in data:
        if userid in line.split():
            validusr=False
            
    password = input("Enter password:")  #input password
    if (not valid_password(password)):
        validpass = False 

    if(validpass and validusr):           #if both are true write to file
        f.writelines(userid+" "+password)
        f.write("\n")
        f.close()
    else:
        print("invaild information")   # if invalid information while loop will continue
        continue
    break                               #only after successful entry while loop will end


Output:
Enter user id:rakesh
Enter password:protect
invaild information
Enter user id:rakesh
Enter password:protect@12

Data in File:
prit aqwsde@12
omk azsxdcfv@
qas qazxswed@
rakesh protect@12
Q.4: Given a file “in.txt” as shown below:
I am Line 1

I am Line 3

What could be the output of following code?
print(file("mine.txt").readlines())

Answer:

Output    (python 2.7)  
[' I am Line 1\n', '\n', ' I am Line 3']

Output (python 3)

TypeError: '_io.TextIOWrapper' object is not callable
Q.5: Write a program that prompts the user for a file name and then reads and prints the contents of the requested file in upper case.

Answer:

Code:
filename = input("Enter file name with extention: ") 3input file name
file = open(filename,"r")    #open file in read mode
text = file.readlines()      
file.close()

for line in text:           #print file content 
    print(line.upper(), end = '') 
print()


Output:
Enter file name with extention: sarojiniPoem.txt
AUTUMN SONG

LIKE A JOY ON THE HEART OF A SORROW,
THE SUNSET HANGS ON A CLOUD;
A GOLDEN STORM OF GLITTERING SHEAVES,
OF FAIR AND TRAIL AND FLUTTERING LEAVES, 
THE WILD WIND BLOWS IN A CLOUD.

HARK TO A VOICE THAT IS CALLING,
TO MY HEART IN THE VOICE OF THE WIND;
MY HEART IS WEARY AND SAD AND ALONE, 
FOR ITS DREAMS LIKE THE FLUTTERING LEAVES HAVE GONE,
AND WHY SHOULD I STAY BEHIND?

SAROJINI NAIDU
Q.6: Write a program that reads a text file and then creates a new file where each character’s case is inverted.

Answer:

Code:
file = open("sarojiniPoem.txt","r")  #open file in read mode
text = file.readlines() 
file.close()

for line in text:
    print(line.swapcase(), end = '')    # change case of string
print()

Output:
aUTUMN sONG

lIKE A JOY ON THE HEART OF A SORROW,
tHE SUNSET HANGS ON A CLOUD;
a GOLDEN STORM OF GLITTERING SHEAVES,
oF FAIR AND TRAIL AND FLUTTERING LEAVES, 
tHE WILD WIND BLOWS IN A CLOUD.

hARK TO A VOICE THAT IS CALLING,
tO MY HEART IN THE VOICE OF THE WIND;
mY HEART IS WEARY AND SAD AND ALONE, 
fOR ITS DREAMS LIKE THE FLUTTERING LEAVES HAVE GONE,
aND WHY SHOULD i STAY BEHIND?

sAROJINI nAIDU
Q.7: Create a file phonebook.det that stores the details in following format:
Name                Phone
Jivin               86666000
Kriti               1010101


Obtain the details from the user.

Answer:

Code:
username = input("Enter user name:")
f = open("phonebook.det", "a")     #open file in append mode
phone = input("Enter phone:")
f.writelines(username+"\t"+phone)  # write to file
f.write("\n")
f.close()

file = open("phonebook.det","r") #reading file
text = file.readlines() 
file.close()

for line in text:               # print file information
    print(line, end = '') 
print()


Output:
Enter user name:omkar
Enter phone:62351478
name     phone
pritesh  12345678
omkar    62351478
Q.8: Write a program to append more details to file “phonebook.det”.

Answer:

Code:
username = input("Enter user name:")
f = open("phonebook.det", "a")     #open file in append mode
phone = input("Enter phone:")
f.writelines(username+"\t"+phone)  # write to file
f.write("\n")
f.close()

file = open("phonebook.det","r") #reading file
text = file.readlines() 
file.close()

for line in text:               # print file information
    print(line, end = '') 
print()


Output:
Enter user name:omkar
Enter phone:62351478
name     phone
pritesh  12345678
omkar     62351478
Q.9: Write a program to edit the phone number of “Arvind” in file “phonebook.det”. If there is no record for “Arvind”, report error.

Answer:

Code:
newphone = input("Enter new phone for Arvind:")
file = open("phonebook.det","r")     #open file in write and read mode
text = file.readlines() 
file.close()
oldphone=""
for line in text:               # print file information
    wordList = line.split()     # create a list of words present in line 
    if(wordList[0]=="Arvind"):  # if name is arvind  
        oldphone = wordList[-1] # get the old phone from taht line
        break
                
import fileinput                # fileinput is used to modify file implace

if(oldphone!=""):               # if oldphone contains some value
    file = fileinput.FileInput("phonebook.det", inplace=True)
    for line in file:
        print(line.replace(oldphone, newphone), end='')  # replace oldphone by new
    file.close()                  
else:
    print("ERROR: name Arvind is not present")       # give error if name is not present    


Output:
Enter new phone for Arvind:10000

Old file content:
name    phone
pritesh    123456789
omkar    124563987
rajesh    4562398
Arvind    125634789
aman    145236987    

New file content:
name    phone
pritesh    123456789
omkar    124563987
rajesh    4562398
Arvind    10000
aman    145236987

Clear Doubts with Computer Tutor
In case you’re facing problems in understanding concepts, writing programs, solving questions, want to learn fun facts | tips | tricks or absolutely anything around computer science, feel free to join CTs learner-teacher community: students.computertutor.in

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You cannot copy content of this page