file handling
file handling
file handling
def countwords(Decode):
text=file.read()
words=text.split()
count={}
if len(word)>=5 :
count[word]=count.get(word,0)+1
return count
print(countwords("Decode.txt"))
2. Write a method/function COUNTlines() in Python to read contents from a text file content.TXT,
and display those lines which have @ any where in the line
def countlines():
count=0
f =open('Test.txt','r')
lines=f.readlines()
for line in lines:
for ch in line:
if line=='@':
count=count+1
print("number of lines having @",count)
print(lines)
f.close()
countlines()
3. Mr. Mahesh is a Python Programmer working in a school. He has to maintain the records of
the sports students. He has created a csv file named sports.csv, to store the details. The
structure of sports.csv is : [sport_id, competition, prize_won] where sport_id, is Sport id (integer)
competition is competition name (string) prize_won is ("Gold", "Silver", "Bronze") Mr. Mahesh
wants to write the following user-defined functions : Add_detail () : to accept the detail of a
student and add to a csv file, "spōrts.csv". Count_Medal () : to display the name of competitions
in which students have won "Gold" medal. Help him in writing the code of both the functions.
Import csv
def Add_detail():
writer = csv.writer(file)
def Count_Medal():
gold_competitions = set()
reader = csv.reader(file)
gold_competitions.add(row[1])
print(competition)
34. (a) (i) What is the main purpose of seek() and tell() method? (ii) Consider a binary file,
Cinema.dat containing information in the following structure: [Mno, Mname, Mtype] Write a
function, search_copy(), that reads the content from the file Cinema.dat and copies all the details
of the "Comedy" movie type to file named movie.dat. OR (b) (i) Give one difference between
write() and writeline() function in text file. (ii) A Binary file, "Items.dat" has the following structure:
[Icode, Description, Price] Where Icode - Item code Description - Detail of item Price - Price of
item Write a function Add_data(), that takes Icode, Description and Price from the user and
writes the information in the binary file "Items.dat".
seek() method
The seek() method in file handling allows you to change the file pointer's position.
The file pointer indicates where the next read or write operation will
occur. seek(offset, from_what) takes an offset (number of bytes) and a reference
point (from_what). from_what can be 0 (beginning of file), 1 (current position), or 2 (end
of file).
Step 2: tell() method
The tell() method returns the current position of the file pointer. This is useful to
know where you are in the file.
import struct movie_struct = 'i50s20s' # 'i' for integer, 's' for string
def search_copy():
try:
while True:
try:
data = infile.read(struct.calcsize(movie_struct))
if mtype == "Comedy":
outfile.write(data)
except struct.error:
except FileNotFoundError:
search_copy()
or
import struct
item_struct = 'i100sf' # 'i' for integer, 's' for string, 'f' for float
def Add_data():
try:
outfile.write(data)
except Exception as e:
Add_data()
28. (A) Write a user defined function in Python named showInLines() which reads contents of a
text file named STORY.TXT and displays every sentence in a separate line. Assume that a
sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!). For example, if
the content of file STORY. TXT is as follows: Our parents told us that we must eat vegetables to
be healthy. And it turns out, our parents were right! So, what else did our parents tell? Then the
function should display the file's content as follows: Our parents told us that we must eat
vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents
tell? OR (B) Write a function, c_words () in Python that separately counts and displays the
number of uppercase and lowercase alphabets in a text file, Words.txt.
import re
def showInLines(filepath="STORY.TXT"):
try:
content = file.read()
except FileNotFoundError:
return
sentences = content.split('. ') #Splitting by '. ' to handle spaces after full stops.
print(sentence + ".") #Add the full stop back if it was removed during splitting.
def showInLines(filepath="STORY.TXT"):
try:
content = file.read()
if not content.strip():
except FileNotFoundError:
return
if sentence:
print(sentence)
b ) def c_words(filepath="Words.txt"):
try:
text = file.read()
except FileNotFoundError:
(b) Write a function RevString() to read a textfile "Input.txt" and prints the words starting with 'O'
in reverse order. The rest of the content is displayed normally. Example: If content in the text file
is : UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM Output will be : UBUNTU IS AN
NEPO SOURCE GNITAREPO SYSTEM (words 'OPEN' and 'OPERATING' are displayed in
reverse order)
def RevString():
try:
# Open the file for reading
content = file.read()
words = content.split()
result = []
else:
print(" ".join(result))
except FileNotFoundError:
import csv
def Add_Device():
try:
writer = csv.writer(csvfile)
except ValueError:
except Exception as e:
def Count_Device():
count = 0
try:
reader = csv.reader(csvfile)
try:
price = int(row[2])
count += 1
except FileNotFoundError:
except Exception as e:
The 'w' mode (write mode) opens a file for writing. If the file exists, its contents are overwritten. If
the file doesn't exist, a new file is created.
The 'a' mode (append mode) opens a file for writing. If the file exists, new data is appended to the
end of the file. If the file doesn't exist, a new file is created.
Assuming item_id is an integer and item_name and amount are strings. The pickle module is used
for binary file handling.
import pickle
def Copy_new():
try:
while True:
try:
record = pickle.load(infile)
pickle.dump(record, outfile)
except EOFError:
break
except FileNotFoundError:
Copy_new()
The with statement ensures that the file is automatically closed, even if errors occur. This prevents
resource leaks and improves code reliability.
Assuming Emp_Id is an integer, Name is a string, and Salary is a float or integer. The pickle module is
used for binary file handling.
import pickle
def disp_Detail():
try:
while True:
try:
record = pickle.load(file)
except EOFError:
break
except FileNotFoundError:
disp_Detail()
Write a function in Python that displays the book names having Y or 'y' in their name from a text
file "Bookname.txt". Example: If the file 'Bookname.txt' contains the names of following books:
One Hundred Years of Solitude The Diary of a Young Girl On the Road After execution, the
output will be : One Hundred Years of Solitude The Diary of a Young Girl
def display_books_with_y():
with open("Bookname.txt", "r") as file:
book_names = file.readlines()
filtered_books = []
for book in book_names:
if 'Y' in book or 'y' in book:
filtered_books.append(book.strip())
def RevString():
try:
# Open the file 'Input.txt' and read its contents
with open("Input.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file 'Input.txt' was not found.")
except Exception as e:
print("An error occurred:", e)
# Example usage
RevString()
38. (a) Write a point of difference between append (a) and write (w) modes in a text file. Write a
program in Python that defines and calls the following user defined functions: (i) Add_Teacher():
It accepts the values from the user and inserts record of a teacher to a csv file 'Teacher.csv'.
Each record consists of a list with field elements as T_id, Tname and desig to store teacher ID,
teacher name and designation respectively. (ii) Search_Teacher(): To display the records of all
the PGT (designation) teachers
iStep 1: Point of Difference between append (a) and write (w) modes
The key difference lies in how they handle existing files:
write (w): Overwrites the entire file. If the file exists, its contents are erased before writing new data.
If the file doesn't exist, it creates a new one.
append (a): Adds new data to the end of the file. If the file exists, the new data is appended; if not, it
creates a new file.
Step 2: Add_Teacher() function definition
This function takes teacher details as input and adds a new record to 'Teacher.csv'. We'll assume the
CSV file has a header row.
import csv
def Add_Teacher():
try:
with open('Teacher.csv', 'a', newline='') as csvfile:
fieldnames = ['T_id', 'Tname', 'desig']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
import csv
def Search_Teacher():
try:
with open('Teacher.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
print("Records of PGT teachers:")
for row in reader:
if row['desig'] == 'PGT':
print(row)
except FileNotFoundError:
print("Teacher.csv not found.")
except Exception as e:
print(f"An error occurred: {e}")
Step 4: Calling the functions
Add_Teacher()
Search_Teacher()
38. (a) Write a point of difference between seek () and tell () functions in a file handling. Write a
program in Python that defines and calls the following user defined functions: (i) Add_Device(): It
accepts and records of a peripherial devices to a csv file peripherial.csv .Each record consists of
a lis with file element as p_id ,P_name and price to store peripherial device ID,device name and
device price respectively. (ii)Count_Device(): To count and display number of peripherial devices
whose price is less than $1000
import csv
except Exception as e:
print("An error occurred:", e)
except FileNotFoundError:
print("The file 'peripheral.csv' does not exist. Please add records first.")
except Exception as e:
print("An error occurred:", e)
# Main program
print("Choose an option:")
print("1. Add Device Records")
print("2. Count Devices with Price < ₹1000")
if choice == 1:
Add_Device()
elif choice == 2:
Count_Device()
else:
print("Invalid choice!")
35. Atharva is a programmer, who has recently been given a task to write a Python code to
perform the following binary file operation with the help of a user defined function/module:
Copy_new(): to create a binary file new_items.dat and write all the item details stored in the
binary file, items.dat, except for the item whose item_id is 101. The data is stored in the following
format: {item_id:[item_name,amount]} import _______________ # Statement 1 def Copy_new():
f1= _______________ # Statement 2 f2= _______________ # Statement 3
item_id=int(input("Enter the item id")) item_detail= _______________ # Statement 4 for key in
item_detail: if _______________ : _______________ # Statement 5 pickle. _______________ #
Statement 6 f1.close() f2.close()
def Copy_new():
f1 = open("items.dat", "rb") # Statement 2: Open the source file in binary read mode
f2 = open("new_items.dat", "wb") # Statement 3: Open the destination file in binary write mode
(a) Write the definition of a Python function named LongLines() which reads the contents of a
text file named 'LINES.TXT' and displays those lines from the file which have at least 10
words in it. For example, if the content of 'LINES.TXT' is as follows: Once upon a time, there
was a woodcutter He lived in a little house in a beautiful, green wood. One day, he was
merrily chopping some wood. He saw a little girl skipping through the woods, whistling
happily. The girl was followed by a big gray wolf. Then the function should display output as:
He lived in a little house in a beautiful, green wood. He saw a little girl skipping through the
woods, whistling happily.
def LongLines():
try:
# Open the file 'LINES.TXT' in read mode
with open("LINES.TXT", "r") as file:
# Read each line from the file
for line in file:
# Split the line into words and count them
word_count = len(line.split())
# Check if the line has at least 10 words
if word_count >= 10:
print(line.strip()) # Print the line after stripping trailing spaces/newlines
except FileNotFoundError:
print("The file 'LINES.TXT' does not exist.")
except Exception as e:
print("An error occurred:", e)
(b) Write a function `count_Dwords()` in Python to count the words ending with a digit in a text file
"Details.txt". Example: If the file content is as follows: On seat2 VIP1 will sit and On seat1 VVIP2
will be sitting Output will be: Number of words ending with a digit are 4
Asked Dec 18 at 12:23
def count_Dwords():
try:
# Open the file "Details.txt" in read mode
with open("Details.txt", "r") as file:
content = file.read() # Read the entire content of the file
# Use regex to find all words ending with a digit
words_with_digits = re.findall(r'\b\w*\d\b', content)
(a) Write one difference between CSV and text files. Write a program in Python that defines
and calls the following user defined functions: (i) COURIER_ADD(): It takes the values
from the user and adds the details to a csv file 'courier.csv'. Each record consists of a list
with field elements as cid, s_name, Source, destination to store Courier ID, Sender
name, Source and destination address respectively. (ii) COURIER_SEARCH(): Takes
the destination as the input and displays all the courier records going to that destination.
OR (b) Why it is important to close a file before exiting? Write a program in Python that
defines and calls the following user defined functions: (i) Add_Book(): Takes the details
of the books and adds them to a csv file 'Book.csv'. Each record consists of a list with
field elements as book_ID, B_name and pub to store book ID, book name and publisher
respectively. (ii) Search_Book(): Takes publisher name as input and counts and displays
number of books published by them.
(b) CSV Files: Store structured data where fields are separated by commas, making it
suitable for tabular data.
(c) Text Files: Store plain text data without any specific format. It may not have
structured data, and each line can contain arbitrary text.
mport csv
if choice == '1':
COURIER_ADD()
elif choice == '2':
COURIER_SEARCH()
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
b
import csv
if choice == '1':
Add_Book()
elif choice == '2':
Search_Book()
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
35. Shreyas is a programmer, who has recently been given a task to write a user defined function
named write_bin() to create a binary file called Cust_file.dat containing customer information
customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each
customer. The function accepts customer number, name, quantity and price. Thereafter, it
displays the message 'Quantity less than 10..... Cannot SAVE', if quantity entered is less than 10.
Otherwise the function calculates amount as price * quantity and then writes the record in the
form of a list into the binary file. import pickle def write_bin(): bin_file= while True:
c_no=int(input("enter customer number")) c_name=input("enter customer name")
qty=int(input("enter qty")) price=int(input("enter price")) if #Statement 2 print("Quantity less than
10..Cannot SAVE") else: amt=price * qty c_detail=[c_no,c_name,qty,price,amt] #Statement 3
ans=input("Do you wish to enter more records y/n") if ans.lower()=='n': #Statement 4 #Statement
5 #Statement 6 (i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of
the customer. 1 (ii) Which statement should Shreyas fill in Statement 2 to check whether quantity
is less than 10. 1 (iii) Which statement should Shreyas fill in Statement 3 to write data to the
binary file and in Statement 4 to stop further processing if the user does not wish to enter more
records. 2
import pickle
def write_bin():
# Statement 1: Open binary file for writing
bin_file = open("Cust_file.dat", "wb")
while True:
# Input customer details
c_no = int(input("Enter customer number: "))
c_name = input("Enter customer name: ")
qty = int(input("Enter quantity: "))
price = int(input("Enter price: "))
# Statement 2: Check if quantity is less than 10
if qty < 10:
print("Quantity less than 10..Cannot SAVE")
else:
# Calculate amount and store details
amt = price * qty
c_detail = [c_no, c_name, qty, price, amt]