0% found this document useful (0 votes)
9 views6 pages

Practicals Cs

The document contains multiple Python scripts for various functionalities including file handling, character counting, record management using CSV and pickle, and stack operations. It demonstrates how to create, read, update, and search records in files, as well as manage a stack data structure. Each section provides a loop for user interaction to perform different operations.

Uploaded by

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

Practicals Cs

The document contains multiple Python scripts for various functionalities including file handling, character counting, record management using CSV and pickle, and stack operations. It demonstrates how to create, read, update, and search records in files, as well as manage a stack data structure. Each section provides a loop for user interaction to perform different operations.

Uploaded by

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

1) # Create a text file and write some content

file = open('sample.txt', 'w')

file.write("Hello World! This is a sample text file.")

file.close()

# Function to count characters

def count_characters(filename):

vowels = consonants = lower = upper = 0

file = open(filename, 'r')

text = file.read()

file.close()

for char in text:

if char.isalpha():

if char.lower() in 'aeiou':

vowels += 1

else:

consonants += 1

if char.islower():

lower += 1

else:

upper += 1

return vowels, consonants, lower, upper

# Count and display the results

vowels, consonants, lower, upper = count_characters('sample.txt')

print(f"Vowels: {vowels}, Consonants: {consonants}, Lowercase: {lower}, Uppercase: {upper}")

2) import csv

def add_record():
with open('telephone.csv', 'a', newline='') as f:

csv.writer(f).writerow([input("Cust ID: "), input("Name: "), input("Phone No: "), input("Plan Type:
")])

def display_records():

with open('telephone.csv', 'r') as f:

for row in csv.reader(f):

print(row)

def search_record(field, value):

with open('telephone.csv', 'r') as f:

for row in csv.reader(f):

if row[field].lower() == value.lower():

print(row)

return

print("Record not found.")

def display_by_start_letter(letter):

with open('telephone.csv', 'r') as f:

for row in csv.reader(f):

if row[1].startswith(letter):

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

while True:

choice = input("\n1. Add Record\n2. Display Records\n3. Search by Cust ID\n4. Search by Name\
n5. Display by Starting Letter\n6. Exit\nChoice: ")

if choice == '1': add_record()

elif choice == '2': display_records()

elif choice == '3': search_record(0, input("Cust ID: "))

elif choice == '4': search_record(1, input("Name: "))

elif choice == '5': display_by_start_letter(input("Starting Letter: "))

elif choice == '6': break


else: print("Invalid choice.")

3)

stack = []

def push():

item = input("Enter item to push: ")

stack.append(item)

print(f"{item} pushed to stack.")

def pop():

if stack:

print(f"Popped item: {stack.pop()}")

else:

print("Stack is empty.")

def display():

print("Stack contents:", stack)

def peek():

if stack:

print("Top item:", stack[-1])

else:

print("Stack is empty.")

while True:

choice = input("\n1. Push\n2. Pop\n3. Display\n4. Peek\n5. Continue (Y/N): ")

if choice == '1': push()

elif choice == '2': pop()

elif choice == '3': display()

elif choice == '4': peek()

elif choice.lower() == '5':


if input("Continue? (Y/N): ").lower() != 'y': break

else: print("Invalid choice.")

4)

import pickle

def write_record():

with open('doctors.dat', 'ab') as f:

doctor_id = input("Enter Doctor ID: ")

doctor_name = input("Enter Doctor Name: ")

salary = float(input("Enter Salary: "))

pickle.dump((doctor_id, doctor_name, salary), f)

def read_records():

try:

with open('doctors.dat', 'rb') as f:

while True:

print(pickle.load(f))

except EOFError:

pass

def update_record():

doctor_id = input("Enter Doctor ID to update: ")

records = []

found = False

try:

with open('doctors.dat', 'rb') as f:

while True:

record = pickle.load(f)

if record[0] == doctor_id:

record = (record[0], record[1], float(input("Enter new Salary: ")))

found = True
records.append(record)

except EOFError:

pass

with open('doctors.dat', 'wb') as f:

for record in records:

pickle.dump(record, f)

if found:

print("Record updated.")

else:

print("Record not found.")

def search_record():

doctor_id = input("Enter Doctor ID to search: ")

try:

with open('doctors.dat', 'rb') as f:

while True:

record = pickle.load(f)

if record[0] == doctor_id:

print(record)

return

except EOFError:

print("Record not found.")

while True:

choice = input("\n1. Write Record\n2. Read Records\n3. Update Record\n4. Search Record\n5.
Continue (Y/N): ")

if choice == '1': write_record()

elif choice == '2': read_records()

elif choice == '3': update_record()

elif choice == '4': search_record()

elif choice.lower() == '5':


if input("Continue? (Y/N): ").lower() != 'y': break

else: print("Invalid choice.")

5)A)

import csv

# Create and write to the CSV file

with open('emp.csv', 'w', newline='') as f:

writer = csv.writer(f)

writer.writerow(['EmpNo', 'Name', 'Salary']) # Header

writer.writerows([

[1, 'Alice', 15000],

[2, 'Bob', 25000],

[3, 'Charlie', 18000],

[4, 'David', 9000],

[5, 'Eve', 12000]

])

# Read and display records with salary in the range of 10000 to 20000

with open('emp.csv', 'r') as f:

reader = csv.reader(f)

next(reader) # Skip header

print("Employees with salary between 10000 and 20000:")

for row in reader:

if 10000 <= int(row[2]) <= 20000:

print(row)

5)B)

with open('hash.txt', 'r') as f:

3 for line in f:

4 print('@'.join(line.split()))

You might also like