0% found this document useful (0 votes)
45 views37 pages

CS 15 Code

The document contains a series of Python programs designed for various tasks such as counting vowels in a text file, copying file contents, capitalizing sentences, and managing student records in binary files. Each program includes input and output examples, demonstrating functionality like reading, writing, and manipulating data. The document serves as a practical guide for implementing file operations and data handling 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)
45 views37 pages

CS 15 Code

The document contains a series of Python programs designed for various tasks such as counting vowels in a text file, copying file contents, capitalizing sentences, and managing student records in binary files. Each program includes input and output examples, demonstrating functionality like reading, writing, and manipulating data. The document serves as a practical guide for implementing file operations and data handling 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

COMPUTER SCIENCE

PYTHON PROGRAMS

NAME : JOBEL SAJI


ABRAHAM

CLASS: 12-B

ADM NO- 10612


1.Program that counts and
displays the number of
vowels in the text file
INPUT ;
def vowel_count():
f = open("hello python.txt", "r")
data = str(f.read())
count = 0
for ch in data:
if ch in "aeiouAEIOU":
count = count + 1
print("No of vowels:", count)
f.close()

vowel_count()
OUTPUT;
No of vowels: 11
2.Program to copy the
contents of the file to
another file.
INPUT :
import os
def fileCopy(file1, file2):
f1 = open(file1, 'r')
f2 = open(file2, 'w')
line = f1.readline()
while line != '':
f2.write(line) # write the line
from f1 into f2
line = f1.readline()
f1.close()
f2.close()

def main():
fileName1 = input("Enter the
source file name: ")
fileName2 = input("Enter the
destination file name: ")
fileCopy(fileName1, fileName2)

if __name__== "__main__":
main()

OUTPUT;
Enter the source file name: test.txt
Enter the destination file name: file2
3.Function to capitalize the
first letter of the sentence
INPUT ;
def capitalize_sentence():
f1 = open("hello python.txt", "r")
f2 = open("file2.txt", "w")

while 1:
line = f1.readline()
if not line:
break
line = line.rstrip()
linelength = len(line)
i=0
str = ""
while i < linelength:
if line[i]== ‘.’:
str = str + line[i].upper()
i=i+1
elif line[i] == '.':
str = str + line[i]
j=i+1
if j < linelength:
str = str + line[j].upper()
i=i+2
else:
i=i+1
else:
str = str + line[i]
i=i+1
f2.write(str + "\n")
else:
print(“source file doesn’t exist”)
f1.close()
f2.close()
print("File copied with capitalized
sentences successfully.")
capitalize_sentence()

OUTPUT;
File copied with capitalized
sentences successfully.
4.Program to store and
display multiple integers in
and from a binary file
INPUT ;
def binfile():
Import pickle
file = open('data.dat', 'wb')
while True:
x = int(input("Enter the integer:
"))
pickle.dump(x, file)
ans = input("Do you want to
enter more data Y/N: ")
if ans.upper() == 'N':
break
file.close()

file = open('data.dat', 'rb')


try:
while True:
y = pickle.load(file)
print(y)
except EOFError:
pass
file.close()

binfile()

OUTPUT;
Enter the integer: 2
Do you want to enter more data Y/N:
Y
Enter the integer: 66
Do you want to enter more data Y/N:
Y
Enter the integer: 6
Do you want to enter more data Y/N:
Y
Enter the integer: 5
Do you want to enter more data Y/N:
N
2
66
6
5
5.Program to append a
record in a binary file
INPUT ;
import pickle

record = []
while True:
roll_no = int(input("Enter student
Roll no: "))
name = input("Enter the student
Name: ")
marks = int(input("Enter the marks
obtained: "))
data = [roll_no, name, marks]
record.append(data)

choice = input("Wish to enter more


records (Y/N)?: ")
if choice.upper() == 'N':
break

f = open("student.dat", "wb")
pickle.dump(record, f)
print("Record Added")
f.close()

OUTPUT;
Enter student Roll no: 2
Enter the student Name: radhika
Enter the marks obtained: 44
Wish to enter more records (Y/N)?: N
Record Added
6.Program to start a record
from the binary file on the
basis of roll no.
INPUT ;
import pickle

f = open("student.dat", "rb")
stud_rec = pickle.load(f) # To read
the object from the opened file
found = 0
rno = int(input("Enter the roll number
to search: "))

for R in stud_rec:
if R[0] == rno:
print("Successful Search:", R[1],
"Found!")
found = 1
break

if found == 0:
print("Sorry, record not found")
f.close()

OUTPUT;
Enter the roll number to search: 5
Sorry, record not found
7.Updating a record in a
binary file using roll no.
INPUT;
import pickle

f = open("student.dat", "rb+")
stud_rec = pickle.load(f)
found = 0
rollno = int(input("Enter the roll
number to search: "))

for R in stud_rec:
rno = R[0]
if rno == rollno:
print("Current Name is:", R[1])
R[1] = input("Enter the New
Name: ")
found = 1
break

if found == 1:
f.seek(0)
pickle.dump(stud_rec, f)
print("Name Updated !!!")

f.close()

OUTPUT;
Enter the roll number to search: 2
Current Name is: radhika
Enter the New Name: sonia
Name Updated !!!
8.Program to read byte by
byte from a file using seek()
and tell().
INPUT ;
f = open("test1.txt")
print("Before reading: ", f.tell())
s=f.read()
print("After reading: ", f.tell())
f.seek(0)
print("From the beginning again: ",
f.tell())
s=f.read(4)
print("First 4 bytes are:", s)
print (f.tell())
s=f.read(3)
print("next 3 bytes: ", s)
print(f.tell())
f.close()
OUTPUT;
Before reading:0
After reading: 45
From the beginning again:0
First 4 bytes are: This
4
next 3 bytes: is
7
9.Program to count the
exact number of record
present in csv file
excluding the header
INPUT;
import csv
f = open("student.csv", 'r')
csv_reader = csv.reader(f)
csvRows=[]
value=0
for row in csv reader:
if csv_reader.line_num == 0:
continue
csvRows.append(row)
value = len(list(csv_reader))
print("No. of records are:", value)
f.close()
OUTPUT;
No. of records are:9
10.Program to write student
data onto marks.csv file
using writerow() method.
INPUT ;
import csv
fields = ['Name', 'Class', 'Year',
'Percent']
rows =[['Rohit', 'XII', '2003', '92'],
['Shaurya', 'XI', '2004', '82'],
['Deep', 'XII', '2002', '80'],
['Prerna', 'XI', '2006', '85'],
['Lakshya', 'XII', '2005', '72']]

filename='marks.csv'
with open (filename, 'w', newline='')
as f:
csv_w=csv.writer(f, delimiter = ',')
csv_w.writerow(fields)
for i in rows:
csv_w.writerow(i)
print("File Created")

OUTPUT;
File created
11.Write a program to
search a student record by
roll number from a binary
file.
INPUT ;
import pickle

def search_roll(rno):
f = open("student.dat", "rb")
found = False
try:
while True:
record = pickle.load(f)
if record[0] == rno:
print("Record found:",
record)
found = True
break
except EOFError:
if not found:
print("Record not found")
f.close()

search_roll(2)

OUTPUT;
Record found: [2, 'Rahul', 76.0]
12.Maintain a binary file with
roll, name, marks. Write
functions to Create file Display
records Search by roll no​
Update marks Delete record

INPUT;
import pickle
import os

FILENAME = "student.dat"

def create_file():
f = open(FILENAME, "wb")
n = int(input("Enter number of
students: "))
for i in range(n):
roll = int(input("Roll No: "))
name = input("Name: ")
marks = float(input("Marks: "))
pickle.dump([roll, name, marks],
f)
f.close()
print("File created successfully.\n")

def display_file():
f = open(FILENAME, "rb")
print("Roll\tName\tMarks")
try:
while True:
rec = pickle.load(f)
print(rec[0], "\t", rec[1], "\t",
rec[2])
except EOFError:
f.close()

def search_record(rno):
f = open(FILENAME, "rb")
found = False
try:
while True:
rec = pickle.load(f)
if rec[0] == rno:
print("Record found:", rec)
found = True
except EOFError:
if not found:
print("Record not found")
f.close()

def update_marks(rno, new_marks):


f = open(FILENAME, "rb")
temp = []
try:
while True:
rec = pickle.load(f)
if rec[0] == rno:
rec[2] = new_marks
temp.append(rec)
except EOFError:
f.close()

f = open(FILENAME, "wb")
for rec in temp:
pickle.dump(rec, f)
f.close()
print("Marks updated.\n")

def delete_record(rno):
f = open(FILENAME, "rb")
temp = []
try:
while True:
rec = pickle.load(f)
if rec[0] != rno:
temp.append(rec)
except EOFError:
f.close()

f = open(FILENAME, "wb")
for rec in temp:
pickle.dump(rec, f)
f.close()
print("Record deleted.\n")

OUTPUT;
Roll Name Marks
1 Alvin 89.5
2 Rahul 76.0
3 Sneha 92.0
Record found: [2, 'Rahul', 76.0]
Marks updated.
Record deleted.
13.Program to read a text
file andCount uppercase &
lowercase letters Count
digits & special characters​

INPUT ;
def analyze_text_file():
f = open("notes.txt", "r")
data = f.read()
f.close()

upper = lower = digits = special = 0


words = data.split()
word_freq = {}

for ch in data:
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
elif ch.isdigit():
digits += 1
elif not ch.isspace():
special += 1

for word in words:


word = word.strip(".,!?").lower()
word_freq[word] =
word_freq.get(word, 0) + 1

print("Uppercase Letters:", upper)


print("Lowercase Letters:", lower)
print("Digits:", digits)
print("Special Characters:",
special)
print("\nWord Frequency:")
for w, f in word_freq.items():
print(w, ":", f)

analyze_text_file()

OUTPUT;
Uppercase Letters: 15
Lowercase Letters: 120
Digits: 8
Special Characters: 12

Word Frequency:
india : 3
is : 5
great : 2
country : 1
14. Program to read a text
file and create another file
containing only those
words that start with a
capital letter.

INPUT;
def extract_capital_words():
f1 = open("story.txt", "r")
f2 = open("capital_words.txt", "w")

for line in f1:


words = line.split()
for w in words:
if w[0].isupper():
f2.write(w + "\n")
f1.close()
f2.close()
print("File 'capital_words.txt'
created successfully.")

extract_capital_words()

OUTPUT;
India
Education
Science
Technology
15.Program to count and
display all records where
the name starts with 'A'.

INPUT;
import pickle

def names_starting_A():
f = open("student.dat", "rb")
count = 0
print("Students whose name starts
with 'A':")
try:
while True:
rec = pickle.load(f)
if rec[1].startswith("A"):
print(rec)
count += 1
except EOFError:
f.close()
print("Total count:", count)

names_starting_A()

OUTPUT;
Students whose name starts with 'A':
[1, 'Alvin', 89.5]
Total count: 1

You might also like