Practical File Cs
Practical File Cs
SCHOOL
COMPUTER SCIENCE
PRACTICAL FILE
BY:- JASMEET SINGH
22 , 12C
➔ 1. Read a text file and display the number of
uppercase/lowercase/vowels/consonants/digits/special characters in
the file.
➔ def count():
f=open("C:\\prac\data.txt","r")
V=C=U=L=D=S=0
data=f.read()
for i in data:
if i.isalpha():
if i.isupper():
U+=1
elif i.islower:
L+=1
elif i.lower() in "aeiou":
V+=1
else:
C+=1
else:
if i.isdigit():
D+=1
else:
S+=1
print("Number of uppercase letters: ",U)
print("Number of lowercase letters: ",L)
print("Number of vowels: ",V)
print("Number of consonants: ",C)
print("Number of digits: ",D)
print("Number of special characters: ",S)
f.close()
count()
➔ OUTPUT:-
➔ 2. Remove all the lines that contain the character 'a' in a file and
write it to another file.
➔ def remove():
f=open("C:\\test\data_old.txt","r")
lines=f.readlines()
fo=open("C:\\test\data_old.txt","w")
fn=open("C:\\test\data_new.txt","w")
if 'a' in line:
fn.write(line)
else:
fo.write(line)
print("Data updated")
remove()
➔ OUTPUT:-
➔ 3. Create a binary file with roll number, name and marks. Input a roll
number and update the marks.
➔ import pickle
def write():
f=open("C:\\test\student.dat","wb")
while True:
record=[r,n,m]
pickle.dump(record,f)
if ch in 'nN':
break
f.close()
def read():
f=open("C:\\test\student.dat","rb")
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def update():
f=open("C:\\test\student.dat","rb+")
rollno=int(input("Enter the roll no. for which you want to update the marks : "))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
except EOFError:
f.close()
write()
read()
update()
read()
➔ OUTPUT:-
➔ import pickle
def add_employee():
with open("employees.dat", "ab") as file:
emp_id = int(input("Enter Employee ID: "))
name = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
date_of_joining = input("Enter Date of Joining (DD-MM-YYYY): ")
employee = {
'ID': emp_id,
'Name': name,
'Salary': salary,
'Date of Joining': date_of_joining
}
pickle.dump(employee, file)
print("Employee record added successfully!\n")
def display_employees():
try:
with open("employees.dat", "rb") as file:
print("Displaying all employee records:")
while True:
try:
employee = pickle.load(file)
print(employee)
except EOFError:
break
except FileNotFoundError:
print("File not found. Please add records first.\n")
def search_employee():
emp_id = int(input("Enter Employee ID to search: "))
found = False
try:
with open("employees.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee['ID'] == emp_id:
print("Employee record found:", employee)
found = True
break
except EOFError:
break
if not found:
print("Employee record not found.\n")
except FileNotFoundError:
print("File not found. Please add records first.\n")
def main():
while True:
print("Menu:")
print("1. Add Employee Record")
print("2. Display All Records")
print("3. Search for an Employee Record")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
add_employee()
elif choice == '2':
display_employees()
elif choice == '3':
search_employee()
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.\n")
main()
➔ OUTPUT:-
➔ import csv
def write():
try:
with open("C:\\test\\sigma.csv", "a", newline='') as f:
wo = csv.writer(f)
f.seek(0)
if f.tell() == 0:
wo.writerow(["UserId", "Password"])
while True:
u_id = input("Enter the User ID: ")
pswd = input("Enter Password: ")
data = [u_id, pswd]
wo.writerow(data)
ch = input("Do you want to enter more? (Y/N): ")
if ch in 'Nn':
break
except Exception as e:
print(f"Error: {e}")
def read():
try:
with open("C:\\test\\sigma.csv", "r") as f:
ro = csv.reader(f)
for i in ro:
print(i)
except FileNotFoundError:
print("File not found. Please write records first.")
def search():
try:
with open("C:\\test\\sigma.csv", "r") as f:
u = input("Enter User ID to search: ")
ro = csv.reader(f)
next(ro)
for i in ro:
if i[0] == u:
print("Password:", i[1])
return
print("User ID not found.")
except FileNotFoundError:
print("File not found. Please write records first.")
write()
read()
search()
➔ OUTPUT:-
➔ 6. MAKE A PYTHON PROGRAM FOR MANAGING BOOK INVENTORY
WITH CSV FILE:
➔ import csv
def write_data():
with open("books.csv", mode='a', newline='') as file:
writer = csv.writer(file)
if file.tell() == 0:
writer.writerow(["Book ID", "Title", "Author", "Price"])
while True:
book_id = input("Enter Book ID: ")
title = input("Enter Book Title: ")
author = input("Enter Author Name: ")
price = input("Enter Price: ")
writer.writerow([book_id, title, author, price])
def read_data():
try:
with open("books.csv", mode='r') as file:
reader = csv.reader(file)
next(reader)
print("\nBook Inventory Records:")
for row in reader:
print(f"Book ID: {row[0]}, Title: {row[1]}, Author: {row[2]}, Price:
{row[3]}")
except FileNotFoundError:
print("The file does not exist. Please add book records first.")
def search_data():
book_id = input("Enter the Book ID to search: ")
found = False
try:
with open("books.csv", mode='r') as file:
reader = csv.reader(file)
next(reader)
for row in reader:
if row[0] == book_id:
print(f"Book Found: ID = {row[0]}, Title = {row[1]}, Author = {row[2]},
Price = {row[3]}")
found = True
break
if not found:
print("Book ID not found.")
except FileNotFoundError:
print("The file does not exist. Please add book records first.")
def main():
while True:
print("\nMenu:")
print("1. Add Book Details")
print("2. View All Book Records")
print("3. Search for a Book by ID")
print("4. Exit")
if choice == '1':
write_data()
elif choice == '2':
read_data()
elif choice == '3':
search_data()
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
➔ OUTPUT:-
➔ 7. Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
➔ import random
while True:
print("="*69)
print("*"*25,"ROLLING THE DICE","*"*25)
print("="*69)
num=random.randint(1,6)
if num==6:
print("YOOO YOU GOT",num,"GGZ")
elif num==1:
print("Oh nah imagine getting",num)
else:
print("Cool you got",num)
ch=input("Roll again? (Y/N):")
if ch in 'Nn':
break
print("*"*25,"THANKS FOR PLAYING","*"*25)
➔ OUTPUT:-
➔ 8. WRITE A PROGRAM TO SHOW IF THE ENTERED STRING IS
PALINDROME OR NOT.
➔ def is_palindrome(s):
cleaned_string = ""
for char in s:
if char != " ":
cleaned_string += char.lower()
if is_palindrome(input_string):
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")
➔ OUTPUT:-
n = int(input("Enter the digit (n) to check for numbers ending with it: "))
values = input("Enter a list of numbers separated by spaces: ").split()
values = [int(x) if x.isdigit() else x for x in values]
result = sum_values_ending_with_n(n, values)
print(f"The sum of numbers ending with {n} is: {result}")
➔ OUTPUT:-
while True:
numbers = list(map(int, input("Enter a list of numbers separated by spaces:
").split()))
choice = input("Do you want to remove 'odd' or 'even' numbers? ").strip().lower()
elif pattern_type == 2:
#Inverted Right-Angled Triangle
for i in range(rows, 0, -1):
print('*' * i)
elif pattern_type == 3:
#Pyramid Pattern
for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
elif pattern_type == 4:
#Inverted Pyramid Pattern
for i in range(rows, 0, -1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
elif pattern_type == 5:
#Square Pattern
for i in range(rows):
print('*' * rows)
elif pattern_type == 6:
#Hollow Square Pattern
for i in range(rows):
if i == 0 or i == rows - 1:
print('*' * rows)
else:
print('*' + ' ' * (rows - 2) + '*')
elif pattern_type == 7:
#Number Pyramid
num = 1
for i in range(1, rows + 1):
print(' ' * (rows - i) + ''.join(str(num + j) for j in range(i)))
num += i
elif pattern_type == 8:
#Reverse Number Pyramid
num = rows * (rows + 1) // 2
for i in range(rows, 0, -1):
print(' ' * (rows - i) + ''.join(str(num - j) for j in range(i)))
num -= i
else:
print("Invalid pattern type selected.")
def main():
print("Pattern Types:")
print("1. Right-Angled Triangle")
print("2. Inverted Right-Angled Triangle")
print("3. Pyramid")
print("4. Inverted Pyramid")
print("5. Square (Filled with stars)")
print("6. Hollow Square")
print("7. Number Pyramid")
print("8. Reverse Number Pyramid")
print("\nPattern Output:")
print_pattern(pattern_type, rows)
if __name__ == "__main__":
main()
➔ OUTPUT:-
➔ 12. WRITE A PROGRAM TO FIND THE NUMBER OF TIMES A
CHARACTER IS USED IN A GIVEN STRING.
➔ OUTPUT:-
➔ 13. WAP to find whether the number entered is an armstrong
number or not.
s=0
temp=num
while (temp>0):
digit=temp%10
s+=digit**3
temp//=10
if (num==s):
else:
➔ OUTPUT:-
➔ class Stack:
def __init__(self):
self.stack = []
def pop(self):
if not self.is_empty():
return self.stack.pop()
return None
def is_empty(self):
return len(self.stack) == 0
def reverse_string(input_string):
stack = Stack()
stack.push(char)
reversed_string = ''
reversed_string += stack.pop()
return reversed_string
if __name__ == "__main__":
reversed_result = reverse_string(original_string)
➔ class PlayerStack:
def __init__(self):
self.stack = []
self.stack.append(player)
def DeletePlayer(self):
if not self.is_empty():
removed_player = self.stack.pop()
else:
def is_empty(self):
return len(self.stack) == 0
def display_stack(self):
if not self.is_empty():
else:
# Example Usage
if __name__ == "__main__":
player_stack = PlayerStack()
while True:
print("4. Exit")
if choice == '1':
player_stack.AddPlayer(player)
player_stack.DeletePlayer()
break
else:
➔ OUTPUT:-