Computer Science Class XII Python File Handling Test Series Part 4

Computer Science Class XII Python File Handling Test Series Part 4


Q1. Write a program in python to read entire content of file ("data.txt")

                                 

Q2. Write a program in python to read first 5 characters from the file("data.txt") 

                            

Q3. Write a program in python to read first line from the file("data.txt")

                               

Q4. Write a program in python to display number of lines in a file("data.txt"). 

                             

Q5. Write a program in python to display first line from the file("data.txt") using readlines(). 

Q6. readlines() function returns the entire data in the form of list of _____

Q7. Name two functions which are used to write data into file.

Q8. Accept five names from the user and write in a file "name.txt"

Q9. Accept five sports names from the user and write in a file "sport.txt" (each name should write in separate line)

Q10. Accept five hobbies from the user and write in a file "hobby.txt" (each hobby should write in separate line) without using write() function.


SOLUTIONS

Q1. Write a program in python to read entire content of file ("data.txt")


                                 

Q2. Write a program in python to read first 5 characters from the file("data.txt") 

                                

Q3. Write a program in python to read first line from the file("data.txt")

                                 

Q4. Write a program in python to display number of lines in a file("data.txt"). 

                                

Q5. Write a program in python to display first line from the file("data.txt") using readlines(). 

                                

Q6. readlines() function returns the entire data in the form of list of _____

Ans. String

Q7. Name two functions which are used to write data into file.

Ans. write() and writelines()

Q8. Accept five names from the user and write in a file "name.txt"

Ans.

f = open("name.txt","w")

for i in range(5):

   n = input("Enter name")

   f.write(n)

f.close()

Q9. Accept five sports names from the user and write in a file "sport.txt" (each name should write in separate line)

f = open("name.txt","w")

for i in range(5):

       n = input("Enter sport name")

       f.write(n)

       f.write('\n')

f.close()

Q10. Accept five hobbies from the user and write in a file "hobby.txt" (each hobby should write in separate line) without using write() function.

Ans.

f = open("hobby.txt","w")

h = [ ]

for i in range(5):

       n = input("Enter hobby name")

       h.append(n,'\n')

f.writelines(h)

f.close()

1 comment:

  1. In last program append method can't take 2 argument at a time.

    ReplyDelete

Most Recently Published

File Handling Test 6

 File Handling Test 6 Q1 . Do we need to use the close() function when we use 'with' statement to open a file? Q2. Which mode you wi...

CS - IP Assignment/Worksheet