[go: up one dir, main page]

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

File_Handling

The document outlines various Python programming tasks related to file handling, including reading from and writing to text and binary files, as well as CSV files. It includes functions for displaying specific lines, counting occurrences of words, and managing employee and product records. Additionally, it discusses the differences between text and binary files and provides examples of how to implement these tasks in Python.
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 views10 pages

File_Handling

The document outlines various Python programming tasks related to file handling, including reading from and writing to text and binary files, as well as CSV files. It includes functions for displaying specific lines, counting occurrences of words, and managing employee and product records. Additionally, it discusses the differences between text and binary files and provides examples of how to implement these tasks in Python.
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/ 10

FILE HANDLING

1. Write a method SHOWLINES() in Python to readlines from text file ‘TESTFILE.TXT’and display
the lines which do not contain 'ke'. Example: If the file content is as follows: An apple a day
keeps the doctor away. We all pray for everyone’s safety. A marked difference will come in
our country. The SHOWLINES() function should display the output as: We all pray for
everyone’s safety.

2. 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 thef ile contents are as follows: Whose
woods these are I think I know. His house is in the village though; 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

3. A binary file “emp.dat” has structure (EID, Ename, designation,salary) Write a function
Show() in Python that would read the details of employees from the file “emp.dat” and
display the details of those employees whose designation is “Manager”

4. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. Write a function
CountRec(Author) in Python which accepts the Author name as parameter and count and
return number of books written by the given Author

5. Write a function in Python to count the number of lines in a text fie ‘EXAM.txt’ which start
with an alphabet ‘T’ .

6. Write a function in Python that count the number of “can” words present in a text file
“DETAILS.txt” .

7. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a
function countrec() in Python that would read contents of the file “salary.DAT” and display
the details of those employee whose salary is above 20000.

8. 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 details of those students whose percentage is above 90. Also display number of
students scoring above 90%

9. Write a function in Python to read a text file, Rhyme.txt and displays those words which have
length more than 5

10. Write a function, in Python that counts the number of lines in text file named “data.txt” and
displays the lines which are starting with “K” or ‘k’.

11. Consider a binary file “book.dat” that has structure [BookNo, Book_Name, Author, Price].
Write a user defined function CreateFile() that takes input data for a record and add to
book.dat

12. How are CSV files different from Binary Files.

Page no. 1 By KUNTAL BANERJEE


FILE HANDLING
13. Consider a binary file “MyFile.dat” that has following structure [ empid, ename and salary].
Write a userdefined function to search records based on the salary entered by the user and if
the salary is more than 25000 then display the record.

14. Gupta is writing a program to create a csv file “employee.csv” which will contain user name
and password for department entries. He has written the following code . As a programmer,
help him to successfully execute the given task.

import ---------------- #statement 1


def add_emp(username,password):
f=open(‘employee.csv’, ’----------‘) # statement 2
content=csv.writer(f)
content.writerow([username,password])
f.close()

def read_emp( ):

with open (‘employee.csv’,’r’) as file:

content_reader=csv.-------------------(file) # statement 3

for row in content_reader:

print(row[0],row[1])

file.close( )

add_emp(‘mohan’,’emp123#’)

add_emp(‘ravi’,’emp456#’)

read_emp() #statement 4

i) Name the module he should import in statement 1


ii) In which mode , Gupta should open the file to add record in to the file ? (statement 2)
iii) Fill in the blank in statement 3 to read the record from a csv file
iv) What output will he obtain while executing statement 4 ?

15. When do you think text file should be preferred over binary file ?

16. A Binary file, DRINKS.DAT has the following structure:

{ DRINKCODE : [DRINKNAME, DRINKPRICE] }

Write a user defined function, finddetails(Dname), that accepts Dname as parameter and
displays all the records from the binary file DRINK.DAT, that have the value of Drink name as
Dname.

17. What type (Text/Binary) of file is Mydata ? Explain Your Answere.

Page no. 2 By KUNTAL BANERJEE


FILE HANDLING
18. A binary file "Players.dat" has structure [Player_code,Player_name, Total_runs].
a) Write a user define function ADD_Player() in python to input data for a record and
add to Players.dat.
b) Write a function ShowPlayer() in python to display all players details whose total
runs more than 8000 from "Players.dat".

19. Tushar is a Python programmer. He has written a code and created a binary file record.dat
with employeeid, ename and salary. The file contains 10 records.

He now has to delete a record based on the employee id entered by the user. For this
purpose, he creates a temporary file, named temp.dat, to store all the records other than the
record to be deleted. If the employee id is not found, an appropriate message should to be
displayed.

As a Python expert, help him to complete the following code (by completing statements 1, 2,
3, and 4) based on the requirement given above:

(i) Complete Statement #1 to import the required module.


(ii) Write the correct statement required to open a temporary file named
temp.dat. (#Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the
binary file, record.dat
(iv) What should be written in Statement4 to write there records in the file
temp.dat?

import _______________________ #Statement1


def update_data():
rec={} fin=open("record.dat","rb")
fout=open("________________","") #Statement2
found=False
eid=int(input("Enter employee id:")) while True:
try:
rec= _____________ #Statement3
if rec["Employee id"]==eid:
found=True
else:
_________________ #Statement 4

except:

break

if found==True:

print("Recorddeleted.")

else: print("Employee with such id is notfound")

fin.close()

fout.close()

Page no. 3 By KUNTAL BANERJEE


FILE HANDLING
20. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT,
and display those words, which are less than 4 characters .

21. A binary file "emp.DAT has structure (EID, Ename,designation,salary). Writea function
addemp() to write three more records of employes in existing file emp.dat. (The details of
the employees must be taken as input from the user.)

22. Consider a CSV file 'INVENTORY.CSV' that stores information about products using the
structure [ProductlD, ProductName, Quantity, Price].

Write the following Python functions for different operations.

addProduct(): To write the product details in the file (Minimum 3 products)

expensiveProducts(): To read the contents of INVENTORY.CSV' and display details of products


with a price higher than Rs. 1000. Additionally, calculate and display the sum of such
expensive products.

For example: If the file stores the following data in binary format

[1, 'ABC, 100, 5000]

[2,'DEF, 250, 1000]

[3, 'GHI, 300, 2000]

then the function should display

Product ID: 1,'ABC, 100, 5000

Product ID: 3, 'GHI, 300, 2000

Total expensive products: 7000

23. A Binary file, CINEMA.DAT has the following structure:


{ MNO:[ MNAME, MTYPE ]}
Where, MNO -Movie Number, MNAME - Movie Name, MTYPE is Movie Type
Wrie a user defincd function, findType(mtype), that accepts mtype as parameter and displays
all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype.

24. Write a python program for operating on a csv file "people.csv" using following functions:

a) addPeople(): To input details of people and add them to a csv file "people.csv"
without removing the previous records. The record structure is as follows:
[AdhrNo, Name, City, Age]

The file should store only those people whose age is greater than and equal to 18.

b) getPeople(): To open the file "people.csv" and display records whose


name starts with "P"

Page no. 4 By KUNTAL BANERJEE


FILE HANDLING
25. A text file contains alphanumeric text (say an.txt). Write a program that reads this text file
and prints only the numbers or digits from the file.

26. Write a function display_oddLines () to display odd number lines from the text file. Consider
above file friends.txt.

27. Write a function COUNT_AND () in Python to read the text file "STORY.TXT" and count the
number of times "AND" occurs in the file. (include AND/and/And in the counting)

28. Write a function DISPLAYWORDS() in python to display the count of words starting with "t"
or "T" in a text file 'STORY.TXT'.

29. A binary file "product.dat" has structure [PNO, PNAME, BRAND_NAME, PRICE] to maintain
and manipulate Product details.

* Write a user defined function CreateFile() to input data for a record and add to
"product.dat" file. The number of records to be entered until the user chooses 'Y' / 'Yes'.

* Write a function CountData(BRAND_NAME) in Python which accepts the brand name as


parameter and count and return number of products by the given brand are stored in the
binary file "product.dat".

30. Write a function ETCount() in Python, which should read each character of a text file
TESTFILE.TXT" and then count and display the count of occurrence of alphabets E and

IT individually (including small cases e and t too)

31. Write a method SHOWLINES() in Python to read lines from text file 'story.txt' and display the
lines which do not contain 'text'.

Example: If the file content is as follows :

Write a function word_of_length (text).

That takes an argument and.

Returns a tuple containing length of each word of text.

This is your program.

The SHOWLINES() function should display the output as:

Page no. 5 By KUNTAL BANERJEE


FILE HANDLING
32. Aryan is a Python programmer working in Infotech Ltd. For the Ambica Furniture, he has
created a csv file named furniture.csv, to store the data of different furnitures.

Write User Defined Functions in Python as per following requirements :

a. ADD () - To accept and add data of an item to a CSV file 'furniture.csv'. Each
record consists of Fur_id, Description, Price, and Discount.

b. COUNTR() - To count the number of records present in 'furniture.csv' whose


price is less than 5000.

33. Mr. Snehant is a software engineer working at TCS. He has been assigned to develop code for
stock management; he has to create a CSV file named stock.csv to store the stock details of
different products.
The structure of stock.csv is: [stockno, sname, price, qty], where stockno is the stock serial
number (int), sname is the stock name (string), price is stock price (float) and qty is quantity
of stock(int).

Mr. Snehant wants to maintain the stock data properly, for which he wants to write the
following user defined functions:

AcceptStock() - to accept a record from the user and append it to the file stock.csv. The
column headings should also be added on top of the csv file. The number of records to be
entered until the user chooses 'Y/'Yes'.

StockReport() to read and display the stockno, stock name, price, qty and value of each stock
as price qty. As a Python expert, help him complete the task.

34. 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, 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

Page no. 6 By KUNTAL BANERJEE


FILE HANDLING

35. 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 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

36. 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)

(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

37. A pre-existing text file data.txt has some words written in it. Write a python function
displaywords() that will print all the words that are having length greater than 3.

If the contents of file is :

A man always wants to strive higher in his life

He wants to be perfect.

The output should be: always wants strive higher life wants perfect.

Page no. 7 By KUNTAL BANERJEE


FILE HANDLING
38. Write a method count_lines() in Python to read lines from text file 'student.txt' and display
the total number of line in file and lines which are ending with 'y' alphabet and not ending
with 'y' separately.

Example: If the file content is as follows:

An apple in a day keeps the doctor away.

We should aware for everyone's safety and security.

India is one of the biggest country in word.

The count_lines() function should display the output as:

The number of lines in file are: 3

The number of lines ending with alphabet 'y' are: 2

The number of lines not ending with alphabet 'y' are: 1

39. What is CSV means? Which packages/modules are imported for using Binary Files and CSV
files in Python?

40. Abhay have a binary file called library.dat containing book information- B_id, B_name and
B_price of each book.

[[B_id, B_name, B_price],[B_id, B_name, B_price],...]

Write the user defined function Trace_Book() to show the records of books having the price
less than 1000. In case there is no book having price <1000 the function displays message
"Such Record not found".

41. Mayur is a student, who have a binary file called STUDENT.DAT containing employee
information-sid, name and age of each student.

[sid, name, age]

Write the user defined function Get_Stud() to display the name and age of those student
who have a age greater than 18 year. In case there is no student having age >18 the function
displays message "There is no student who is greater than 18 year".

42. 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:

Page no. 8 By KUNTAL BANERJEE


FILE HANDLING
The train from Andaman has earned the name 'Floating Train'. What is so unique about this
train 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

43. Write code in Python to implement the concept of Stack and in continuation write a function
in Python, Push(S,E) Which takes an Element (E) of a dictionary Cosmetic where, Cosmetic
containing the details of products- {Pname:price).

The function should push the names of those products in the stack whose price is greater
than 130. Also display the count of elements pushed into the stack.

For example:

If the dictionary contains the following data:

Ditem = {"Face Wash":105, "Facepack": 150, "Cleansing Milk": 130,"Sunscreen": 180,


"FaceMask":115}

The stack should contain

Facepack

Sunscreen

The output should be:

The count of elements in the stack is

44. Rajat is working on a language statistics project. He has to analyze the writings of a famous
English novelist. He has downloaded a text file named 'russel.txt' containing major writings
of the author. He is stuck at the problem of counting the number of words starting with 'th'
or 'Th". Being a computer science student, help Rajat by writing a function countWords() in
python to count the number of words starting with "Th' or 'th' in the text file 'russel.txt'.

45. Vijay has created a csv file 'FOOTBALL.CSV' to store player name, matches and goals scored.

Write a program in python that defines and calls following user defined functions.

i. addPlayer(name, matches, goals): Three parameters - name of the


player, matches played and goals scored are passed to the function.
The function should create a list object and append it to the csv file.

Page no. 9 By KUNTAL BANERJEE


FILE HANDLING
ii. highestAverage(): The function should read the csv file and display
the name of the player with the highest average goals
(goals/matches).

46. Shweta had stored all her passwords in one binary file named 'PASSWORDS.DAT'. The
passwords were stored in following format:

[app_name, username, password]

Write a function search(app) that accepts title as a parameter and displays the username
arid password for that particular app.

47. Neha has a very large text file named 'log_report.txt' which contains more than 50,000 log
entries for logins on a local ssh server. Following is a truncated view of the file log_report.txt.

2022-10-14:22:40:39 Login failed > from 192.168.11.16

2022-10-14:22:20:19 Login success > from 192.168.11.220

2022-10-14:10:14:40 Login success > from 192.168.0.66

2022-10-13:11:19:17 Login failed > from 192.168.0.45

2022-10-14:22:40:39 Login success > from 192.168.11.156

...
...

Neha has asked you to help her count the number of failed login attempts. Write a function
countFailedAttempts() in python to count the number of lines containing the word 'failed in
the text file 'log_report.txt'.

Page no. 10 By KUNTAL BANERJEE

You might also like