getting-started-files/questions.rst
author Nishanth <nishanth@fossee.in>
Sun, 10 Oct 2010 15:40:19 +0530
changeset 292 de96931fac21
parent 245 3ed6ef2ea91f
child 345 d82151cc11f5
permissions -rw-r--r--
reviewed questions

Objective Questions
-------------------

.. A mininum of 8 questions here. 

1. What function is used to open a file?

   Answer: ``open``

#. The ``open`` function returns a 

   a. string
   #. list
   #. file object
   #. function

   Answer: file object

#. ``open`` function opens a file by default in write mode. T or F?
   
   Answer: False

#. The ``read`` method reads a file and returns the contents

   a. string
   #. list
   #. file object
   #. None of the above

   Answer: string

#. Given a file with ``hello.txt``, which looks like 
   ::
     
     Hello, World!

   What is the value of content, at the end of this code block::

     f = open('hello.txt')
     pre_content = f.read()
     content = f.read()
     f.close()

   Answer: It is a null string. 

#. The following code block prints each line of ``hello.txt``::

     f = open('hello.txt')
     for line in f.read():
         print line

   True or False?

   Answer: False

#. Given a file with ``hello.txt``, which looks like 
   ::
     
     Hello, World!

   What is the output of ::

     f = open('hello.txt')

     for line in f:
         print line

     for line in f:
         print line

     f.close()

   Answer: Hello, World! is printed once.

           .. The actual answer should talk about blank lines, but I'm
           .. not sure if we should get into such detail. 

           .. Should this be made a multiple-choice?

   
#. Given a file with ``hello.txt``, which looks like 
   ::
     
     Hello, World!

   What is the output of ::

     f = open('hello.txt')

     for line in f:
         print line

     f.close()

     for line in f:
         print line

     f.close()

   Answer: Hello, World! is printed twice.

#. Given a file with ``hello.txt``, which looks like 
   ::
     
     Hello, World!

   What is the output of ::

     f = open('hello')

     for line in f:
         print line

     f.close()

     for line in f:
         print line

     f.close()

   Answer: IOError - No such file or directory: 'hello'


Larger Questions
----------------

.. A minimum of 2 questions here. 

1. What does ``f.read(size)`` do?

#. Print every alternate line of a file, starting at the first line. 

#. Print the file in reverse. Starting from the last line to the
   first.