0% found this document useful (0 votes)
3 views5 pages

Python File Handling and Data Structures

The document contains multiple Python functions for various tasks including reading and processing text files, counting characters, managing binary files for student records, simulating dice rolls, implementing a stack, and handling CSV files for user credentials. Each function is designed to perform specific operations such as counting vowels, updating records, and searching for user IDs. The code examples demonstrate basic file handling, data manipulation, and user interaction 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)
3 views5 pages

Python File Handling and Data Structures

The document contains multiple Python functions for various tasks including reading and processing text files, counting characters, managing binary files for student records, simulating dice rolls, implementing a stack, and handling CSV files for user credentials. Each function is designed to perform specific operations such as counting vowels, updating records, and searching for user IDs. The code examples demonstrate basic file handling, data manipulation, and user interaction 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/ 5

1.

Read a Text File and Display Words Separated by #

def WordSeparated():
with open("Quote.txt", "r") as f:
for line in f:
words = line.split()
for word in words:
print(word, '#', end='')
print()
WordSeparated()

2. Count Vowels, Consonants, Uppercase, and Lowercase Characters

def CountVCUL():
with open("Report.txt", "r") as f:
data = f.read()

V = C = U = L = 0
for i in data:
if i.isalpha():
if i.isupper():
U += 1
if i.islower():
L += 1
if i.lower() in 'aeiou':
V += 1
else:
C += 1

print("Vowels =", V)
print("Consonants =", C)
print("Uppercase =", U)
print("Lowercase =", L)
CountVCUL()

3. Remove Lines Containing 'a' and Save to Another File

def Remove():
with open("SampleOld.txt", "r") as f:
lines = f.readlines()

with open("SampleOld.txt", "w") as fo, open("SampleNew.txt", "w") as fn:


for line in lines:
if 'a' in line or 'A' in line:
fn.write(line)
else:
fo.write(line)
print("Data updated in SampleOld.txt and created SampleNew.txt.")
Remove()
4. Binary File - Search by Roll Number

import pickle

def write():
with open("StudentDetails.dat", "wb") as f:
while True:
r = int(input("Enter Roll No. : "))
n = input("Enter Name : ")
D = {'Roll No': r, 'Name': n}
pickle.dump(D, f)
ch = input("More? (Y/N): ")
if ch.lower() == 'n':
break

def search():
found = False
rollno = int(input("Enter roll no to search: "))
with open("StudentDetails.dat", "rb") as f:
try:
while True:
rec = pickle.load(f)
if rec['Roll No'] == rollno:
print("Name:", rec['Name'])
found = True
break
except EOFError:
pass
if not found:
print("Sorry... No record found.")
write()
search()

5. Binary File - Update Marks by Roll Number

import pickle

def Write():
with open("StudentDetails.dat", 'wb') as f:
while True:
r = int(input("Enter Roll No. : "))
n = input("Enter Name : ")
m = int(input("Enter Marks : "))
record = [r, n, m]
pickle.dump(record, f)
ch = input("More? (Y/N): ")
if ch.lower() == 'n':
break

def Read():
print("Reading records from file:")
with open("StudentDetails.dat", 'rb') as f:
try:
while True:
rec = pickle.load(f)
print(rec)
except EOFError:
pass

def Update():
found = False
rollno = int(input("Enter roll no to update marks: "))
records = []
with open("StudentDetails.dat", 'rb') as f:
try:
while True:
rec = pickle.load(f)
records.append(rec)
except EOFError:
pass
with open("StudentDetails.dat", 'wb') as f:
for rec in records:
if rec[0] == rollno:
rec[2] = int(input("Enter updated marks: "))
found = True
pickle.dump(rec, f)
if not found:
print("Record not found...")
Write()
Read()
Update()
Read()

6. Dice Rolling Simulator

import random

while True:
print("=" * 75)
print("******************* ROLLING THE DICE **********************")
print("=" * 75)

num = random.randint(1, 6)
if num == 6:
print("Hey... you got", num, ".... Congratulations!!!")
elif num == 1:
print("Well tried.... But you got", num)
else:
print("You got:", num)

ch = input("Roll again? (Y/N): ")


if ch.lower() == 'n':
break
print("Thanks for playing!")
7. Stack Implementation Using List

def isEmpty(stk):
return len(stk) == 0

def Push(stk, elt):


stk.append(elt)
print("Element inserted.")
print("Stack:", stk)

def Pop(stk):
if isEmpty(stk):
print("Stack is empty. Underflow!")
else:
print("Deleted Element:", stk.pop())
print("Stack:", stk)

def Peek(stk):
if isEmpty(stk):
print("Stack is empty.")
else:
print("Top Element:", stk[-1])

def Display(stk):
if isEmpty(stk):
print("Stack is empty.")
else:
print("Stack (top to bottom):", stk[::-1])

stack = []
while True:
print("\n...... STACK OPERATIONS ......")
print("1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. DISPLAY")
print("5. EXIT")
ch = int(input("Enter your choice: "))
if ch == 1:
element = int(input("Enter element to push: "))
Push(stack, element)
elif ch == 2:
Pop(stack)
elif ch == 3:
Peek(stack)
elif ch == 4:
Display(stack)
elif ch == 5:
break
else:
print("Invalid choice.")
8. CSV File - User ID and Password Search

import csv

def write():
with open("details.csv", 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["UserId", "Password"])
while True:
u_id = input("Enter User ID: ")
pswd = input("Enter Password: ")
writer.writerow([u_id, pswd])
ch = input("More? (Y/N): ")
if ch.lower() == 'n':
break

def read():
with open("details.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)

def search():
u_id = input("Enter User ID to search: ")
found = False
with open("details.csv", "r") as f:
reader = csv.reader(f)
next(reader) # Skip header
for row in reader:
if row[0] == u_id:
print("Password:", row[1])
found = True
break
if not found:
print("Sorry... No record found.")

write()
read()
search()

You might also like