0% found this document useful (0 votes)
7 views15 pages

File Handling Revision Notes Question Bank

The document provides a comprehensive overview of file handling in Python, detailing the steps involved in opening, processing, and closing files. It explains different file access modes (read, write, append), types of files (text and binary), and methods for reading and writing data, including the use of the CSV module. Additionally, it includes a question bank and programming exercises related to file handling concepts.

Uploaded by

muthuganesh4646
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

File Handling Revision Notes Question Bank

The document provides a comprehensive overview of file handling in Python, detailing the steps involved in opening, processing, and closing files. It explains different file access modes (read, write, append), types of files (text and binary), and methods for reading and writing data, including the use of the CSV module. Additionally, it includes a question bank and programming exercises related to file handling concepts.

Uploaded by

muthuganesh4646
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

PEARLS PUBLIC SCHOOL (CBSE)

ARUMUGANERI
STANDARD XII
FILE HANDLING - REVISION NOTES

What Is File Handling In Python?

Files are named location on the disk used to store data permanently.
Files are non-volatile in nature. Python offers a wide range of methods to handle
the files stored on the disk, we can perform various operation like reading,
writing, editing files stored in computer permanent storage though python
programs.

File Handling Steps


1. Open the File
2. Process the file (Read/write/append)
3. Close the file
4. Opening a file:

Opening A File

To perform any kid of operation on a file, the programmer first need to


open the file by using open() method.

Syntax:

<file_object_name>=open(<filename>,<mode>)

File Pointer: File pointer/file handler is reference to the file on the disk which is
being opened.

File Path: The Location of the file on the disk


File Access Mode: This specifies the nature of operation(read/write/append) to
be performed on the file.

File Access Modes

Read Mode: when a file is opened in read mode then the file must exist,
otherwise python will raise an I/O error.

Write Mode: When a file is opened in write mode and if the file does not exist
then a new file will be created at the specified location on the disk with the same
name. If the file exist on the disk, then the file will be truncated, the user can
overwrite new data into the file.

Append Mode: When a file is opened in append mode and if the file does not
exist then a new file will be created at the specified location on the disk with the
same name. If the file exist on the disk, then the file’s exixting data will be
retained and new data can be appended at the end of the file.

Closing a File
The close() method is used to close an opened file, the execution of close()
method breaks the reference of the file object to file on disk, so after execution of
close() method no operation on the file can be performed, without reopening the
file.
Syntax: <fileHandle>.close()
File Handling and File Types

Python offers wide range of modules/methods to perform file handling


operation on both Text File and Binary File

Text File:

Text files stores the information on the file as sequence of ASCII or Unicode
characters. These files can be open in any text editor in a human readable form.

Binary File:

Binary files stores information as a sequence of bytes, Binary files stores


the information in the same format as it is stored in the memory.

Text File Handling:

Reading a Text File:

We can use any of these 3 methods/functions In order to perform read operation


on a text file:
read([n])
readline([n])
readlines()

read() method:

read() function is used to read contents of a text file and returns the result
as a string. If invoked with argument n it returns n number of bytes(characters)
from file.

Syntax:

<file_object>.read([n])

readline() method:
This function is used to read a line of input text file and returns the result as
a string. If argument n specified then reads at n bytes(characters) of the current
line.
Syntax:
<file_object>.readline([n])

readlines() method:
This function is reads all the line of the input text file and returns each line
as string encapsulated inside a List.

Syntax:
<file_object>.readlines()

Writing into a Text File:


Python provides these two functions for writing into a text file

Appending into a Text File:

When a file is opened in append mode, then new data can be added
into the file without erasing the existing old data in the file, the new data will be
appended at the end of the existing data. To open a file append mode, file mode
need to be set as append “a” while executing open() method.

Binary File Handling

Binary files can store more structured python objects like list, tuple,
dictionary by converting these objects into byte stream( called
serialization/pickling), these objects can brought back to original form while
reading the file (called unpickling).

Pickle module is very useful when it come to binary file handling. We will
use dump() and load() methods of pickle module to write and read data objects
into binary files.
Writing into a binary file:

The dump() function of pickle module can be used to write an object into a
binary file.

Syntax: pickle.dump( <object_to_be_witten>, <filehandle>)

Reading a binary file

To read from a binary file the load() method of the pickle module can be
used. This method unpickles the data from the binary file(convert binary stream
into original object structure).

Syntax: <object>=pickle.load(<filehandle>)

Comma Separated File (CSV) File Handling

CSV stands for “Comma Separated Values.” It is used to store data in a


tabular form in a text file. The fact that CSV files are actually text files, It becomes
very useful to export high volume data to a database or to a server.

Reading/Writing operations on a CSV file can be performed using the csv


module of python. to use the methods of csv module we have to import the csv
module into our program.

Writing into a csv File

As csv file is basically a text file, to write into a csv file mode “w” must be
specified along with the file path in the open() method to open the file.

f=open(`C:\\myfolder\\new.csv’,`w’)
After the file is being open and a file handle is created, we need to create a
writer object using writer() method.

<writerObject>=csv.writer(<fileHandle>)

The writerow() method can be used to write a List object into the csv file.

<writerObject>.writerow(<[List]>)

Reading From a csv File

To read data from a csv file, the file need to opened in the same way as any
text file ( Note: The file extension is .csv)

f=open(`C:\\myfolder\\new.csv’,`r’)

After the file is being open and a file handle is created, we need to create a
reader object using reader() method.

<readerObject>=csv.reader(<fileHandle>)

Once created, a reader object carries all data from the referenced csv file.
QUESTION BANK
Which of the following mode in file opening statement does not generate an error if the file does
1. not exist?
(a) r (b) r+ (c) w+ (d) None of the above
Which of the following is the correct usage for tell() of a file object?
(a) It places the file pointer at the desired offset in a file.
2 (b)It returns the byte position of the file pointer as an integer.
(c)It returns the entire content of the file.
(d) It tells the details about the file.
Which method is used to move the file pointer to a specified position.
3
a. tell() b. seek() c. seekg() d. tellg()
4 What does CSV stand for?
Which of the following statement is incorrect?
(a) A file handle is a reference to a file on disk.
5 (b) File handle is used to read and write data to a file on disk.
(c) All the functions that you perform on a disk file can’t be performed through file handle.
(d) None of these
Which of the following statement is not true regarding opening modes of a file?
(a) When you open a file for reading, if the file does not exist, an error occurs.
6 (b) When you open a file for writing, if the file does not exist, an error does not occur.
(c) When you open a file for appending content, if the file does not exist, an error does not occur.
(d) When you open a file for writing, if the file exists, new content added to the end of the file.
Assertion(A): Access mode ‘a’ opens a file for appending content at the end of the file.
7
Reason(R): The file pointer is at the end of the file if the file exists and opens in write mode.
Which of the following command is used to move the file pointer 2 bytes ahead from the current
8 position in the file stream named fp?
a) fp.seek(2, 1) b) fp.seek(-2, 0) c) fp.seek(-2, 2) d) fp.seek(2, -2)
Which of the following is not a function of csv module?
9
a) readline() b) writerow() c) reader() d) writer()
Assertion (A):- Text file stores information in ASCII or UNICODE characters.
10
Reasoning (R):- In text file there is no delimiter(EOL) for a line.
Which of the following does not return a sting in case of text files?
11
a) read() b) readlines() c) readline() d) reader()
What happens when the following statement is executed and file story.txt is not present in current
directory?
12 fin=open('story.txt','r')
a) Python creates a new file story.txt b) Raises FileNotFoundError
c) Raises IOError d) Opens file in read mode
What does the following statement do : f.seek(5,1)
a) move file pointer 5 characters ahead from start of file
13 b) move file pointer 5 characters ahead from current position in file
c) move file pointer 5 characters ahead from end of file
d) file pointer stays where it is.
Write a statement in Python to perform the following operations:
14 i. To open a text file "MYPET.TXT" in write mode.
ii. To open a text file "MYPET.TXT" in read mode
Assertion (A): CSV files are used to store the data generated by various social media platforms.
15
Reason (R): CSV file can be opened with MS Excel.
Which of the following function returns current position of the file pointer?
16
a. flush() b. tell() c. seek() d. offset()
Consider the Python statement: f.seek(10, 1)
Choose the correct statement from the following:
(a) file pointer will move 10 byte in forward direction from beginning of the file
17
(b) file pointer will move 10 byte in forward direction from end of the file
(c) file pointer will move 10 byte in forward direction from current location
(d) file pointer will move 10 byte in backward direction from current location
Which of the following function returns a list datatype?
18
a) d=f.read() b) d=f.read(10) c) d=f.readline() d) d=f.readlines()
How do you change the file position to an offset value from the start?
19
(a) fp.seek(offset, 0) (b) fp.seek(offset, 1) (c) fp.seek(offset, 2) (d) None of them
Which function is used to write a list of strings in a file?
20
a) writeline( ) b) writelines( ) c) write() d) writeall( )
Assertion(A): Python overwrites an existing file or creates a non- existing file when we open a file
21 with ‘w’ mode.
Reason(R): a+ mode is used only for writing operations
Which of the following mode in file opening statement overwrite the existing content?
22
(a) a+ (b) r+ (c) w+ (d) None of the above
Assertion (A): CSV (Comma Separated Values) is a file format for data storage with one record on
each line and each field is separated by comma.
23
Reason (R): The format is used to share data between cross platform as text editors are available
on all platforms
Which pickle module method is used to read a Python object to a binary file?
24
a. read( ) b. readline( ) c. read_object( ) d. None of the above
Which of the following statements correctly explain the function of seek( ) method?
a. Tells the current position within the file
25 b. Determines if you can move the file cursor position or not.
c. Indicates that the next read or write occurs from that poistion in a file
d. Move the current file position to a given specified position.
1. Write a program to count the words “to” and “the” present in a text file “python.txt”
A text file “PYTHON.TXT” contains alphanumeric text. Write a program that reads this text file and
2
writes to another file “PYTHON1.TXT” entire file except the numbers or digits in the file
Suppose the contents of text file quotes.txt is:
“Believe you can and you will!”
What will be the output of the following python code?
3 F=open(“quotes.txt”)
F.seek(17)
S=F.read()
print(S.split(‘o’))
4 What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
a) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record
5 consists of a list with field elements as empid, name and mobile to store employee id,
employee name and employee salary respectively.
b) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
6 Give any one point of difference between a binary file and a csv file
Write a Program in Python that defines and calls the following user defined functions:
a) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists
7 of a list with field elements as fid, fname and fprice to store furniture id, furniture name and
furniture price respectively.
b) search()- To display the records of the furniture whose price is more than 10000.
Write a python program to create a csv file dvd.csv and write 10 records in it Dvdid, dvd name,
8
qty, price. Display those dvd details whose dvd price is more than 25
Write a function in Phyton to read lines from a text file visiors.txt, and display only those lines,
which are starting with an alphabet 'P'.
If the contents of file is :
Visitors from various cities are coming here.
9
Particularly, they want to visit the museum.
Looking to learn more history about countries with their cultures.
The output should be:
Particularly, they want to visit the museum.
Write a method in Python to read lines from a text file book.txt, to find and display the occurrence
of the word 'are'. For example, if the content of the file is:
10 Books are referred to as a man’s best friend. They are very beneficial for mankind and have
helped it evolve. Books leave a deep impact on us and are responsible for uplifting our mood.
The output should be 3.
Write a Program in Python that defines and calls the following user defined functions:
(i) InsertRow() – To accept and insert data of an student to a CSV file ‘class.csv’. Each \
record consists of a list with field elements as rollno, name and marks to store roll
11
number, student’s name and marks respectively.
(ii) COUNTD() – To count and return the number of students who scored marks greater
than 75 in the CSV file named ‘class.csv’.
A binary file “Book.dat” has structure *BookNo, Book_Name, Author, Price+.
i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
12
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file “Book.dat”
A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a
13 function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the
details of those students whose percentage is above 75. Also display number of students scoring
above 75%
(a) Write a method COUNT_W5() in Python which read all the content of a text file ‘STORY.TXT’
and count &display all those words whose length is 6 character long.
For Example: - If the file content is as follows:
God made the mother earth and the man made countries;
14
These countries having states and states consists cities.
Then the output of the method will be
Six characters words are: - mother, These, having, states,cities,output,method
The total no of words with length of 6 characters is: 6
Write a function VC_COUNT() in Python, which should read each character of a text file
“THEORY.TXT” and then count and display all the vowels and consonants separately(including
upper cases and small cases).
Example:
15 If the file content is as follows:
A boy is playing there. There is a playground.
The VC_COUNT() function should display the output as:
Total vowels are: 14
Total consonants are: 22
Write a program in Python that defines and calls the following user defined functions:
(i) INSERT() – To accept and add data of a Student to a CSV file ‘Sdetails.csv’. Each record
consists of a list with field elements as RollNo, Name, Class and Marks to store roll
16
number of students, name of student, class and marks obtained by the student.
(ii) COUNTROW() – To count the number of records present in the CSV file named
‘Sdetails.csv’.
17 How CSV files are different from normal text files?
Write syntax to create a reader object and write object to read and write the content of a CSV
18
File?
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘empdata.csv’. Each
19 record consists of a list with field elements as Eid, Ename, Salary and City to store
employee id , employee name, employee salary and city.
(ii) SEARCH()- To display the records of the employees whose salary is more than 50000.
Write a method COUNTWORDS() in Python to read data from text file ‘ARTICLE.TXT’ and
display the count of words which ends with a vowel.
For example, if the file content is as follows:
20
An apple a day keeps you healthy and wise
The COUNTWORDS() function should display the output as:
Total words which ends with vowel = 4
Deepali is creating a python program for a Library and created a csv file Books.csv to store the
details of books. The structure of Books.csv is: [BookID, Title, Author, Price] Where
BookID stores Book ID (integer) , Title stores the title of book (string) , Author stores the author of
the book (string) , Price stores the price of the book (float)
21 She wants to write code for the following user defined functions:
(i) AddBook() – to accept a record from the user and add it to the file Book.csv.
(ii) TotalCost() – to read the csv file Book.csv, convert the price of each book into float data type,
find and display the sum of prices of all the books
As a Python expert, help her complete the task.
Sanjay is working on a binary file, PRODUCTS.DAT, containing records of the following
22 structure: ,‘PID’:Product ID, ‘PNAME’:Product Name , ‘PRICE’:Product Price-
Help him to write the following user defined functions:
(i) appendData(), that reads the values of Product ID, Product Name and Product price
from the user into a dictionary and append it into binary file PRODUCTS.DAT.
(ii) findProduct(product_id) that accepts product_id as argument to read binary file
PRODUCTS.DAT and display the details of that product
23 Differentiate between ‘w’ and ‘a’ file modes in Python
Consider a binary file, FASHION.DAT, containing records of the following structure: [GID, GNAME,
FABRIC, PRICE] Where GID – Garment ID , GNAME – Garment Name , FABRIC – Type of fabric i.e.
24 COTTON, SILK, SATIN etc. , PRICE – Price of the garment
Write a user defined function, searchFashion(cost), that accepts cost as parameter and displays all
the records from the binary file FASHION.DAT, that have price more than 1500.
Define a function display_words () in python to read lines from a text file PARA.TXT, and display
25
those words, whose length is more than 5.
Write a user defined function in python that displays the number of lines starting with word 'It' in
26
the file story.txt
Write a function read_binary() that reads records from a binary file “staff.dat” and prints the
27 records whose salary is greater than 5000. The file contains records in the form of a tuple (Staffid,
name, designation, salary)
Write a function countwords( ) that read a file ‘python.txt’ and display the total number of words
which begins by uppercase character.
Example:
28
Suppose the file have following text:
‘Python is a powerful, user friendly and platform independent Language’
Output of function should be : 2
Write a python function ALCount(), which should read each character of text file “STORY.TXT” and
then count and display the number of lines which begins from character ’a’ and ‘l’ individually
(including upper cases ‘A’ and ‘L’ too)
Example:
Suppose the file content is as below:
29 A python is a powerful
Language is user friendly
It is platform independent Language
Output of function should be :
A or a: 1
L or l : 1
Write a user – defined function countH() in Python that displays the number of lines starting with
‘H’ in the file ‘Para.txt”. Example , if the file contains:
Whose woods these are I think I know.
30 His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
Output: The line count should be 2.
Write a function countmy() in Python to read the text file “DATA.TXT” and count the number of
times “my” occurs in the file. For example , if the file “DATA.TXT” contains –
31 “This is my website. I have displayed my preference in the CHOICE section.” The countmy( )
function should display the output as:
“my occurs 2 times”
Write a program in Python that defines and calls the following functions:
Insert() – To accept details of clock from the user and stores it in a csv file ‘watch.csv’. Each record
32
of clock contains following fields – ClockID, ClockName, YearofManf, Price. Function takes details
of all clocks and stores them in file in one go.
Delete() – To accept a ClockID and removes the record with given ClockID from the file ‘watch.csv’.
If ClockID not found then it should show a relevant message. Before removing the record it should
print the record getting removed
33 Differentiate between r+ and w+ file modes in Python
Consider a file STUDENT.DAT, containing records of the following structure:
[RollNumber, Name, Marks]
34 Write a function copyData(), that reads contents from the file STUDENT.DAT and copies the
records with marks more than 60 to the file named ‘HIGHACHIEVERS.DAT’. The function should
return number of records copied to the file HIGHACHIEVERS.DAT.
35 How are text file different from binary files?
A Binary file BANK.DAT has the following structure:
{CNO:[CNAME,ATYPE]}
Where
CNO-Customer account number
36
CNAME-Customer name
ATYPE-Account type
Write a user defined function findType(atype), that accepts atype as parameter and displays all
the records from the binary file BANK.DAT, that have the value of Account type as atype.
Write a function COUNT_AND () in Python to read the text file “STORY.TXT” and count the number
37
of times “AND” occurs in the file. (include AND/and/And in the counting)
Write a function DISPLAYWORDS( ) in python to display the count of words starting with “t” or
38
“T” in a text file ‘STORY.TXT’
Asutosh Das is a Python programmer working in a school. For the preboard results, he has created
a csv file named Result.csvhas following structure [rollno, name, marks].
i. Write a user defined function insertRec () to input data for a student and add to Result.csv.
39
ii. Write a function searchRollNo (r) in Python which accepts the student’s rollno as parameter and
searches the record in the file “Result.csv” and shows the details of student i.e., rollno, name and
marks (if found) otherwise shows the message as ‘No record found’
40 Differentiate between r+ and a+ file modes in Python
Consider a file, SPORTS.DAT, containing records of the following structure:
[SportName, TeamName, No_Players, No_matcheswon]
41 Write a function, copyData (), that reads contents from the file SPORTS.DAT and copies the
records with Sport name as “Cricket” to the file named CRICKET.DAT. The function should return
the total number of records copied to the file CRICKET.DAT.
42 Difference between seek() and tell() methods with syntax
Consider a binary file emp.dat having records in the form of dictionary.
E.g ,eno:1, name:” Rahul”, sal: 5000-
43
write a python function to display the records of above file for those employees who get salary
between 25000 and 30000
Define a function SHOWWORD () in python to read lines from a text file STORY.TXT, and display
44
those words, whose length is less than 5
Write a user defined function in python that displays the number of lines starting with 'H' in the
45
file para.txt
Write a Python program in Python to search the details of the employees (name, designation and
46 salary) whose salary is greater than 5000. The records are stored in the file emp.dat. consider each
record in the file emp.dat as a list containing name, designation and salary.
Write a function in Python to count the number of lines in a text fie ‘EXAM.txt’ which start with an
47
alphabet ‘T’
Write a function in Python that count the number of “can” words present in a text file
48
“DETAILS.txt”
A binary file “salary.DAT” has structure *employee id, employee name, salary]. Write a function
49 countrec() in Python that would read contents of the file “salary.DAT” and display the details of
those employee whose salary is above 20000.
50 What is the difference between ‘r’ and ‘rb’ mode in Python file
A binary file “STUDENT.DAT” has structure *admission_number, Name, Percentage]. Write a
function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the
51
details of those students whose percentage is above 90. Also display number of students scoring
above 90%
Write a method beginA() in Python to read lines from a text file Notebook.TXT, and display those
lines, which are starting with ‘A’.
For example If the file content is as follows:
An apple a day keeps the doctor away.
52 We all pray for everyone’s safety.
A marked difference will come in our country.
The beginA() function should display the output as:
An apple a day keeps the doctor away.
A marked difference will come in our country.
Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a CSV file ‘empdata.csv’. Each record consists
53 of a list with field elements as eid, ename and salary to store emp id, emp name and emp salary
respectively.
(ii) search()- To display the records of the emp whose salary is more than 10000.
Write a function in python to count the number of lines in a text file ‘Country.txt’
which are starting with an alphabet ‘W’ or ‘H’.
For example, If the file contents are as follows……………:
Whose woods these are I think I know.
His house is in the village though;
54
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
Write a user defined function to display the total number of words present in a text file
'Quotes.txt'.
For example: if the file contents are as follows:
Living a life you can be proud of doing your best Spending your time with people and activities
55
that are important to you Standing up for things that are right even when it’s hard Becoming the
best version of you.
The countwords() function should display the output as:
Total number of words : 40
Write a Program in Python that defines and calls the following user defined functions:
a) ADDPROD() – To accept and add data of a product to a CSV file product.csv’.
56 Each record consists of a list with field elements as prodid, name and price to store product id,
employee name and product price respectively.
b) COUNTPROD() – To count the number of records present in the CSV file named ‘product.csv’.
57 Differentiate between Binary File and CSV File
write a python code to perform the following binary file operations with the help of two user
defined functions/modules:
58
a. AddStudents() to create a binary file called STUDENT.DAT containing student information – roll
number, name and marks (out of 100) of each student.
b. GetStudents() to display the name and percentage of those students who have a percentage
greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent.
Write a function COUNT() in Python to read from a text file 'Gratitude.txt'and display the count of
the words ending with letter 'e' in each line Example: If the file content is as follows:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
59 In moments big and small, it's truly known.
The COUNT() function should display the output as:
Line 1 : 2
Line 2 : 0
Line 3 : 3
Line 4 : 0
Write a function VOWEL_WORDS which reads a text file TESTFILE.TXT and then count and display
the number of words starting with vowels ‘a’ or ‘u’ (including capital cases A and U too)
For example is the text in the file TESTFILE.txt is :
The train from Andaman has earned the name ‘Floating Train’. What is so unique about this train
60
to receive such a name?
The expected output is :
The Number of words starting with letter ‘a’ is : 3
The Number of words starting with letter ‘u’ is : 1
Consider a binary file 'STUDENTS.DAT' that stores information about students using a tuple with
the structure (StudentID, StudentName, Course, GPA). Write a Python function
`high_gpa_students` to read the contents of 'STUDENTS.DAT' and display details of students with a
GPA higher than 3.5. Additionally, calculate and display the total count of such high-GPA students.
For example: If the file stores the following data in binary format
(1, 'SURAJ', ‘BCA’, 6.2)
61
(2, 'RAVI', ‘MCA’, 3.0)
(3, ‘KRISH’, ‘BSC’, 7.5)
Then the function should display :
Student Id : 1
Student Id : 3
Total Students scoring high GPA : 2
Consider a file `BOOKS.DAT` containing multiple records. The structure of each record is as
follows:
62 [ISBN, Title, Author, Price, Genre]
Write a Python function named `copy_books` that copies all records from `BOOKS.DAT` where the
genre is 'Mystery' into a new file named `MYSTERY_BOOKS.DAT`.
Consider a Binary file `MOVIES.DAT` containing a dictionary with multiple elements. Each element
is in the form `MNO:[MNAME, MTYPE, RATING]` as a key:value pair where:
- `MNO` – Movie Number
- `MNAME` – Movie Name
63 - `MTYPE` - Movie Type
- `RATING` – Movie Rating
Write a user-defined function, `find_high_rated_movies(rating)`, that accepts a rating as a
parameter and displays all records from the binary file `MOVIES.DAT` where the movie rating is
more than or equal to the rating value passed as a parameter.
Consider a file, Movie.DAT, containing records of the following structure:
64
[MovieName, Banner, YearofRelease]
Write a function, CaptureData(), that reads contents from the file Movie.DAT and copies the
records with Banner as “YashRaj” to the file named Yashrajfilms.DAT. The function should return
thetotal number of records copied to the file Yashrajfilms.DAT.
Vihaan is a Python programmer working in a school. For the Annual Sports Event, he has created a
csv file named Sports.csv, to store theresults of students in different sports events. The structure
of Sports.csv is :
[Player_Id, Player_Name, Game, Result]
Where
Player_Idis Player ID (integer)
Player_nameis Player Name (string)
65 Game is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Winner', 'Defeated'or 'NO result'
For efficiently maintaining data of the event, Vihaan wants to write thefollowing user defined
functions:
input() – to input a record from the user and add it to the file Sports.csv. The column
headings should also be added on top of the csv file.
Winner_Count()– to count the number of player who have won any event.
As a Python expert, help him complete the task.
Write a function in Python to read a text file, Story.txtand displays those lines which begin with
66
the word ‘Once’
A binary file “emp.dat” has structure (EID, Ename, designation,salary) Write a function Show() in
67 Python that would read the details of employees from the file “emp.dat” and display the details of
those employees whose designation is “Manager”
68 What is the difference between readline() and readlines()

You might also like