You are on page 1of 2

REVISION: File Handling

1. Differentiate between text file and binary file.


2. Write the various file mode constants that can be used with open( ) function
and their meaning.

R, rb
R+, rb+

W, wb
W+, wb+

A,ab
A+, ab+

3. Compare and contrast between read(), readline() and readlines() function.


4. Differentiate between write () and writelines () function.
5. Write the significance and syntax of tell() and seek() function.
6. Write a try …. except statement that attempts to open a file for reading and
catches the exception thrown when the file does not exist.
7. file = open('textfile.txt','w')
word = ''
while word.upper() != 'END':
word = input('Enter a word use END to quit')
file.write(word + '\n')
file.close()
In the code (given in question no. 1) the word END used to indicate end of
word list is also stored in the file. Modify the code so that end is not stored in the
file.

8. Write a program to read a file 'Story.txt' and create another file, storing an
index of Story.txt telling which line of the file each word appears in. If word
appears more than once, then index should show all the line numbers
containing the word.
9. Write a function called replace file(), that takes pattern string, replacement
string and two file names as argument. The function should read the first file
and write the content into second file (creating it, if necessary). If the pattern
string appear anywhere in first file, it should be replaced by replacement
string in second file.
10. Reading a file line by line from beginning is a common task, what if you
want to read a file backward. This happens when you need to read log files.
Write a program to read and display content of file from end to beginning.
11. Consider a binary file’student.dat’ which contains the records of students
such as name, rollno, class and marks. Write a program in python to
print the records of only those students from the file who score marks greater than
60%.
12. Given a pickled file called ‘colony.dat’ containing the details of a colony.
The strucutre of a colony is as:
class colony ( colony_code string, colony_name string, no_of_people int)
Write a function in python to update the file with a new value of
no_of_people as per their colony_code. The value of colony_code and
no_of_people are read during the execution of the program.
13. Given a text file VINTAGE.txt containing following information of cars
VNo, VDesc, Vprice. Write a python function to display details of all those
Vintage vehicles which are priced between 200000 and 250000.
14. A file sports.dat contains information in following format: Event-Participant.
Write a function in python that would read contents from file sports.dat and
creates a file named Atheletic .dat copying only those records from sports.dat
where the event name is ‘Atheletics’.
1

You might also like