Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

file handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

1.

Write a method/function COUNTWORDS () in Python to read contents from a text file


DECODE.TXT, to count and return the occurrence of those words, which are having 5 or more
characters.

def countwords(Decode):

with open('Decode.txt','r') as file:

text=file.read()

words=text.split()

count={}

for word in words:

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

Had an amazing time at the comcert last night


with @MusicLoverScrew.
Excited to announce the launch of our new website
G20 @India
Output should be :
Had an amazing time at the comcert last night
with @MusicLoverScrew.
G20 @India

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():

sport_id = int(input("Enter Sport ID: "))

competition = input("Enter Competition Name: ")

prize_won = input("Enter Prize Won (Gold, Silver, Bronze): ")

with open('sports.csv', 'a', newline='') as file:

writer = csv.writer(file)

writer.writerow([sport_id, competition, prize_won])

print("Details added successfully.")

def Count_Medal():

gold_competitions = set()

with open('sports.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:


if row[2] == "Gold":

gold_competitions.add(row[1])

print("Competitions where Gold medals were won:")

for competition in gold_competitions:

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:

with open("Cinema.dat", "rb") as infile, open("movie.dat", "wb") as outfile:

while True:

try:

data = infile.read(struct.calcsize(movie_struct))

mno, mname, mtype = struct.unpack(movie_struct, data)

mtype = mtype.decode().strip() # Decode bytes to string and remove trailing whitespace

if mtype == "Comedy":
outfile.write(data)

except struct.error:

break # End of file

except FileNotFoundError:

print("Cinema.dat not found.")

search_copy()

or

(i) Difference between write() and writelines()


Step 1: write()
The write() method writes a single string to a file.
Step 2: writelines()
The writelines() method writes a list of strings to a file. Each string in the list is
written to a new line.

import struct

item_struct = 'i100sf' # 'i' for integer, 's' for string, 'f' for float

def Add_data():

icode = int(input("Enter Item Code: "))

description = input("Enter Description: ").encode() # Encode string to bytes

price = float(input("Enter Price: "))

data = struct.pack(item_struct, icode, description, price)

try:

with open("Items.dat", "ab") as outfile: # 'ab' for append binary

outfile.write(data)

print("Data added successfully.")

except Exception as e:

print(f"An error occurred: {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:

with open(filepath, 'r') as file:

content = file.read()

except FileNotFoundError:

print(f"Error: File '{filepath}' not found.")

return

sentences = content.split('. ') #Splitting by '. ' to handle spaces after full stops.

sentences = [s.strip() for s in sentences] #Removing leading/trailing spaces.

for sentence in sentences:

if sentence: #Avoid printing empty lines

print(sentence + ".") #Add the full stop back if it was removed during splitting.

def showInLines(filepath="STORY.TXT"):

try:

with open(filepath, 'r') as file:

content = file.read()

if not content.strip():

print("Error: File is empty.")


return

except FileNotFoundError:

print(f"Error: File '{filepath}' not found.")

return

sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)[\s]', content)

for sentence in sentences:

if sentence:

print(sentence)

b ) def c_words(filepath="Words.txt"):

try:

with open(filepath, 'r') as file:

text = file.read()

except FileNotFoundError:

print(f"Error: File '{filepath}' not found.")

return 0, 0 #Return 0 for both counts if file not found.

uppercase_count = sum(1 for char in text if char.isupper())

lowercase_count = sum(1 for char in text if char.islower())

print("Uppercase letters:", uppercase_count)

print("Lowercase letters:", lowercase_count)

return uppercase_count, lowercase_count

(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

with open("Input.txt", "r") as file:

content = file.read()

# Split the content into words

words = content.split()

# Process each word

result = []

for word in words:

if word.upper().startswith('O'): # Check if word starts with 'O'

result.append(word[::-1]) # Reverse the word

else:

result.append(word) # Keep the word as is

# Join and print the final output

print(" ".join(result))

except FileNotFoundError:

print("The file Input.txt was not found.")


32. Sangeeta is a Python programmer working in a computer hardware company. She has to
maintain the records of the peripheral devices. She created a csv file named Peripheral.csv, to
store the details. The structure of Peripheral.csv is: [P_id, P_name, Price] where P_id is
Peripheral device ID (integer) P_name is Peripheral device name (String) Price is Peripheral
device price (integer) Sangeeta wants to write the following user defined functions: Add_Device
(): to accept a record from the user and add it to a csv file, Peripheral.csv. Count_Device(): To
count and display number of peripheral devices whose price is less than 1000.

import csv

def Add_Device():

try:

P_id = int(input("Enter Peripheral ID: "))

P_name = input("Enter Peripheral Name: ")


Price = int(input("Enter Price: "))

with open('Peripheral.csv', 'a', newline='') as csvfile:

writer = csv.writer(csvfile)

writer.writerow([P_id, P_name, Price])

print("Device added successfully!")

except ValueError:

print("Invalid input. Please enter numeric values for ID and Price.")

except Exception as e:

print(f"An error occurred: {e}")

def Count_Device():

count = 0

try:

with open('Peripheral.csv', 'r') as csvfile:

reader = csv.reader(csvfile)

next(reader) #skip header if present.

for row in reader:

try:

price = int(row[2])

if price < 1000:

count += 1

except (ValueError, IndexError):

print("Warning: Skipping row with invalid data.")

print(f"Number of devices with price less than 1000: {count}")

except FileNotFoundError:

print("Error: Peripheral.csv not found.")

except Exception as e:

print(f"An error occurred: {e}")

Add_Device() #Add a new device

Count_Device() #Count devices with price < 1000A


34. (A) (i) Differentiate between 'w' and 'a' file modes in Python. (ii) Consider a binary file,
items.dat, containing records stored in the given format: {item_id: [item_name, amount]} Write a
function, Copy_new(), that copies all records whose amount is greater than 1000 from items.dat
to new_items. dat. OR (B) (i) What is the advantage of using with clause while opening a data file
in Python? Also give syntax of with clause. (ii) A binary file, EMP.DAT has the following structure:
[Emp_Id, Name, Salary] where Emp_Id: Employee id Name: Employee Name Salary: Employee
Salary Write a user defined function, disp_Detail(), that would read the contents of the file
EMP.DAT and display the details of those employees whose salary is below 25000.

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.

The primary difference is that 'w' overwrites, while 'a' appends.

(A) (ii) Copying records from items.dat to new_items.dat

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:

with open('items.dat', 'rb') as infile, open('new_items.dat', 'wb') as outfile:

while True:

try:

record = pickle.load(infile)

if int(record[1][1]) > 1000: #Check if amount > 1000

pickle.dump(record, outfile)

except EOFError:

break
except FileNotFoundError:

print("items.dat not found.")

Copy_new()

(B) (i) Advantages of the with clause

Advantage of with clause

The with statement ensures that the file is automatically closed, even if errors occur. This prevents
resource leaks and improves code reliability.

with open('filename', 'mode') as file_object:

(B) (ii) Displaying employee details from EMP.DAT

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:

with open('EMP.DAT', 'rb') as file:

while True:

try:

record = pickle.load(file)

if record[2] < 25000:

print(f"Emp_Id: {record[0]}, Name: {record[1]}, Salary: {record[2]}")

except EOFError:

break

except FileNotFoundError:

print("EMP.DAT not found.")

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())

for book in filtered_books:


print(book)

# Call the function


display_books_with_y()

def RevString():
try:
# Open the file 'Input.txt' and read its contents
with open("Input.txt", "r") as file:
content = file.read()

# Split the content into words


words = content.split()

# Process each word: Reverse the word if it starts with 'O'


modified_words = [
word[::-1] if word.startswith('O') else word for word in words
]
# Join the modified words back into a single string
result = " ".join(modified_words)

# Print the output


print(result)

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)

#Check if the file is empty to write header


csvfile.seek(0)
first_char = csvfile.read(1)
if not first_char:
writer.writeheader()

T_id = input("Enter Teacher ID: ")


Tname = input("Enter Teacher Name: ")
desig = input("Enter Designation: ")
writer.writerow({'T_id': T_id, 'Tname': Tname, 'desig': desig})
print("Teacher record added successfully!")
except Exception as e:
print(f"An error occurred: {e}")
Step 3: Search_Teacher() function definition
This function reads the 'Teacher.csv' file and displays records of teachers with the designation "PGT".

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

# Function to add device records to 'peripheral.csv'


def Add_Device():
try:
# Open the file in append mode to add new records
with open('peripheral.csv', 'a', newline='') as file:
writer = csv.writer(file)

# Input device details


while True:
p_id = input("Enter Peripheral Device ID: ")
p_name = input("Enter Peripheral Device Name: ")
price = float(input("Enter Price of the Device: "))

# Write record to CSV file


writer.writerow([p_id, p_name, price])

# Ask if the user wants to continue


cont = input("Do you want to add another record? (yes/no): ").lower()
if cont != 'yes':
break
print("Records added successfully!")

except Exception as e:
print("An error occurred:", e)

# Function to count and display devices with price < ₹1000


def Count_Device():
try:
count = 0
# Open the file in read mode
with open('peripheral.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
if len(row) == 3: # Ensure valid data format
try:
price = float(row[2])
if price < 1000:
count += 1
except ValueError:
continue # Skip rows with invalid price data
print(f"Number of devices with price less than ₹1000: {count}")

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")

choice = int(input("Enter your choice (1/2): "))

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()

import pickle # Statement 1

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

# Read the original binary file content


try:
item_detail = pickle.load(f1) # Statement 4: Load the dictionary from the binary file
for key in item_detail:
if key != 101: # Statement 5: Check if the key (item_id) is NOT 101
pickle.dump({key: item_detail[key]}, f2) # Statement 6: Write valid records to
new_items.dat

print("Items except for item_id 101 have been copied to new_items.dat")


except EOFError:
print("End of file reached.")
except Exception as e:
print("An error occurred:", e)
finally:
f1.close() # Close the source file
f2.close() # Close the destination file

# Function Call Example


Copy_new()

(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)

# Call the function to display the output


LongLines()

(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

import re # Import regular expressions for pattern matching

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)

# Count the number of matching words


count = len(words_with_digits)

# Print the words and the count


print("Words ending with a digit are:", words_with_digits)
print("Number of words ending with a digit are:", count)
except FileNotFoundError:
print("The file 'Details.txt' does not exist.")
except Exception as e:
print("An error occurred:", e)

# Call the function


count_Dwords()

(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

# Function to add courier records to 'courier.csv'


def COURIER_ADD():
try:
# Open the CSV file in append mode
with open('courier.csv', 'a', newline='') as file:
writer = csv.writer(file)
# Input courier details
cid = input("Enter Courier ID: ")
s_name = input("Enter Sender's Name: ")
source = input("Enter Source Address: ")
destination = input("Enter Destination Address: ")
# Write the record to the file
writer.writerow([cid, s_name, source, destination])
print("Record added successfully!")
except Exception as e:
print("An error occurred:", e)

# Function to search courier records by destination


def COURIER_SEARCH():
try:
# Open the CSV file in read mode
with open('courier.csv', 'r') as file:
reader = csv.reader(file)
destination_input = input("Enter the destination to search for: ")
found = False
print(f"Couriers going to '{destination_input}':")
for row in reader:
if row and row[3] == destination_input: # Check destination column
print(row)
found = True
if not found:
print("No records found for the given destination.")
except FileNotFoundError:
print("The file 'courier.csv' does not exist. Add records first.")
except Exception as e:
print("An error occurred:", e)

# Menu to call functions


while True:
print("\n1. Add Courier Record")
print("2. Search Courier by Destination")
print("3. Exit")
choice = input("Enter your choice: ")

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

# Function to add book records to 'Book.csv'


def Add_Book():
try:
# Open the CSV file in append mode
with open('Book.csv', 'a', newline='') as file:
writer = csv.writer(file)
# Input book details
book_ID = input("Enter Book ID: ")
B_name = input("Enter Book Name: ")
pub = input("Enter Publisher: ")
# Write the record to the file
writer.writerow([book_ID, B_name, pub])
print("Book record added successfully!")
except Exception as e:
print("An error occurred:", e)

# Function to search books by publisher


def Search_Book():
try:
# Open the CSV file in read mode
with open('Book.csv', 'r') as file:
reader = csv.reader(file)
publisher_input = input("Enter the Publisher's name to search for: ")
count = 0
print(f"Books published by '{publisher_input}':")
for row in reader:
if row and row[2] == publisher_input: # Check publisher column
print(row)
count += 1
print(f"Total books published by '{publisher_input}': {count}")
except FileNotFoundError:
print("The file 'Book.csv' does not exist. Add records first.")
except Exception as e:
print("An error occurred:", e)

# Menu to call functions


while True:
print("\n1. Add Book Record")
print("2. Search Books by Publisher")
print("3. Exit")
choice = input("Enter your choice: ")

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]

# Statement 3: Write data to the binary file


pickle.dump(c_detail, bin_file)

# Ask user to continue or stop


ans = input("Do you wish to enter more records (y/n)? ")

# Statement 4: Stop further processing


if ans.lower() == 'n':
break

# Statement 5: Close the binary file


bin_file.close()
print("Data saved successfully in Cust_file.dat")

# Call the function


write_bin()

You might also like