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

Python File2

The document contains multiple Python programs demonstrating file handling, including reading from and writing to text and binary files, as well as CSV files. It includes functionalities such as counting words, vowels, and consonants, managing employee and student records, and performing CRUD operations on binary files. Each program is structured with user-driven menus for ease of interaction.

Uploaded by

jsaanvi0722
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)
9 views17 pages

Python File2

The document contains multiple Python programs demonstrating file handling, including reading from and writing to text and binary files, as well as CSV files. It includes functionalities such as counting words, vowels, and consonants, managing employee and student records, and performing CRUD operations on binary files. Each program is structured with user-driven menus for ease of interaction.

Uploaded by

jsaanvi0722
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/ 17

Program 13: Write a program to show and count the number of words in a text file „DATA.

TXT‟ which
is starting/ended with an word “The”, “the”

f1=open("data.txt","r")
s=f1.read()
print("All Data of file in string : \n",s)
print("="*30)
count=0
words=s.split()
print("All Words: ",words,", \nlength is ",len(words))
for word in words:
if word.startswith("the")==True: # word.ends with(“the”)
count+=1
print("Words start with 'the' is ",count)
OUTPUT:

„‟‟Program 14: Write a menu driven program in python using text file to
(a) To count the vowels and consonants
(b) To count the no. of words “to” in the file
(c) To display the line that begin with a given letter'''

fob=open(r'data.txt', 'r')
text=fob.read()
text=text.replace('\n', '')
while True:
print("""Select
a to count vowels and consonants in the file
b to count the number of occurrences of a word
c to display the line that begins with a given letter
d to Exit""")
ask=input("Enter your choice : ")
if ask.lower()=='a':
v=c=0
for char in text:
if char.isalpha():
if char.lower() in ['a', 'e', 'i', 'o', 'u']:
v+=1
elif char.lower() not in ['a', 'e', 'i', 'o', 'u']:
c+=1
print('The number of vowels is ', v)
print('The number of consonants is ', c)
print()
elif ask.lower()=='b':
search=input("Enter word to be searched: ")
allwords=text.split(sep=' ')
count=0
for word in allwords:
if word.lower()==search.lower():
count+=1
print("The number of occurrences of the word '", search, "' is ", count)
print()
elif ask.lower()=='c':
letter=input("Enter the letter to be searched: ")
fob.seek(0)
lines=fob.readlines()
lcount=0
for line in lines:
if line[0].lower()==letter.lower():
lcount+=1
print(line)
print()
print("The number of lines starting with ", letter, " is equal to ", lcount)
print()
elif ask.lower()=='d':
print('Exiting console. Thank You!')
break
else:
print('Invalid input')
continue

OUTPUT:
'''Program 15: Write a program to write a string in the binary file “comp.dat” and count the
number of times a character appears in the given string using a dictionary.'''

import pickle
str="This is the Computer Science with Python Class"
f1=open('comp.dat','wb')
pickle.dump(str,f1)
print("The string is written in the ",f1.name, "file")
f1.close()
f1=open('comp.dat','rb')
str=pickle.load(f1)
print("\nThe string in the binary file is : \n",str)
d={}
for x in str:
if x not in d:
d[x]=1
else:
d[x]=d[x]+1
print("\nThe occurrences of each letter of string is :\n", d)
f1.close()

OUTPUT:

„‟‟Program 16: Write a program that will write a string in binary file "school.dat" and
display the words of the string in reverse order.
Example: myString="Silicon Institute of Technology"
Output: Technology of Institute Silicon'''

import pickle
str="This is the Class of Computer Science with Python "
f1=open('school.dat','wb')
pickle.dump(str,f1)
print("The string is written in the ",f1.name, "file\n")
f1.close()
print("------------------------------ Method I ------------------------------")
f1=open('school.dat','rb')
str1=pickle.load(f1)
print("\nThe string in the binary file is : \n",str1)
str1=str1.split(" ")
l=list(str1)
print("\nThe list is : \n",l)
l.reverse()
print("\nThe reverse is : \n",l)
print("------------------------------ Method II ------------------------------")
f1=open('school.dat','rb')
str1=pickle.load(f1)
print("\nThe string in the binary file is : \n",str1)
str1=str.split(" ")
l=list(str1)
print("\nThe list is : \n",l)
length=len(l)
print("\nThe reverse is :")
while length>0:
print(l[length-1],end=" ")
length-=1

OUTPUT:

„‟‟Program 17: '''Write a program to insert list data in CSV File and print it.'''

import csv # importing the csv module


fields = ['Name', 'Branch', 'Year', 'CGPA'] # field names
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
filename = "MYCSV.csv" # name of csv file
with open(filename, 'w') as csvfile: # writing to csv file
csvwriter = csv.writer(csvfile) # creating a csv writer object
csvwriter.writerow(fields) # writing the fields
csvwriter.writerows(rows) # writing the data rows
with open('MYCSV.csv', newline='') as File:
reader = csv.reader(File)
for row in reader:
print(row)

'''Program 18: Write a menu-driven program implementing user-defined functions to perform different
functions on a csv file “student” such as:
(a) Write a single record to csv
(b) Write all the records in one single go onto the csv.
(c) Display the contents of the csv file.'''

import csv
# To create a CSV File by writing individual lines
def CreateCSV1():
# Open CSV File
Csvfile = open('student.csv', 'a', newline='')
# CSV Object for writing
Csvobj = csv.writer(Csvfile)
print("Enter Single Record : ")
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Line = [Rno, Name, Marks]
# Writing a line in CSV file
Csvobj.writerow(Line)
Csvfile.close() # Closing a CSV File
# To create a CSV File by writing all lines in one go
def CreateCSV2():
# Open CSV File
Csvfile = open('student.csv', 'a', newline='')
# CSV Object for writing
Csvobj =csv.writer(Csvfile)
Lines = []
print("Enter Multiple Records : ")
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Lines.append([Rno, Name, Marks])
Ch = input("More(Y/N)?")
if Ch == 'N' or Ch=='n':
break
# Writing all lines in CSV file
Csvobj.writerows(Lines)
Csvfile.close() # Closing a CSV File
# To read and show the content of a CSV File
def ShowAll():
# Opening CSV File for reading
Csvfile = open('student.csv', 'r', newline='')
# Reading the CSV content in object
Csvobj = csv.reader(Csvfile)
for Line in Csvobj: # Extracting line by line content
print(Line)
Csvfile.close() # Closing a CSV File
print("CSV File Handling")
while True:
print("""
1:CreateCSV using input single record
2:CreateCSVAll input multiple records
3:ShowCSV
4:Quit \n""")
Option=int(input("Enter Your Choice : "))
if Option == 1:
CreateCSV1()
elif Option == 2:
CreateCSV2()
elif Option == 3:
ShowAll()
elif Option == 4:
print("Exiting")
break
else:
print("Invalid input")
continue
'''Program 19: Write a menu-driven program to perform all the basic operations using List on
Employee binary file such as inserting, reading, updating, searching and deleting a record.
(Note: Each employee record contains [empno, ename, salary])'''
import pickle
def write_record():
f=open("employ.dat",'ab')
ans='y'
while ans=='y':
eno=int(input("Enter the employee no : "))
ename=input("Enter the employee name : ")
esal=int(input("Enter the employee salary : "))
pickle.dump([eno,ename,esal],f)
ans=input("\nAdd more records(y/n) : ")
f.close()
def display_record():
f=open("employ.dat",'rb')
print("Emp No\tName\tSalary")
while True:
try:
e=pickle.load(f)
for i in e:
print(i,end='\t')
print()
except EOFError:
break
print()
f.close()
def search_record():
f=open("employ.dat",'rb')
found=0
en=int(input("Enter the employee number to be searched "))
while True:
try:
e=pickle.load(f)
if e[0]==en:
print("Employee found!",e,sep='\n')
found=1
break
except EOFError:
if found==0:
print("Not a valid employee number")
break
f.close()
def Update_record():
f=open("employ.dat",'rb+')
found=0
en=int(input("Enter the employee number to be updated : "))
while True:
try:
pos=f.tell()
e=pickle.load(f)
if e[0]==en:
sal=int(input("Enter the salary to be updated"))
e[2]=sal
f.seek(pos)
pickle.dump(e,f)
found=1
print("Record Updated")
break
except EOFError:
if found==0:
print("Record not found")
break
f.close()
def Delete_record():
import os
f1=open("employ.dat",'rb')
f2=open("employ1.dat",'wb')
f=0
en=int(input("Enter the emplyee number to be deleted : "))
while True:
try:
e=pickle.load(f1)
if e[0]!=en:
pickle.dump(e,f2)
if e[0]==en:
f=1
except EOFError:
if f==0:
print("Record not found")
else:
print("Record deleted")
break
f1.close()
f2.close()
os.remove("employ.dat")
os.rename("employ1.dat","employ.dat")
while True:
print("1:Enter record")
print("2:Update record")
print("3:Delete Record")
print("4:Search Record")
print("5:Display Record")
ch=int(input("\nEnter your choice : "))
if ch==1:
write_record()
elif ch==2:
Update_record()
elif ch==3:
Delete_record()
elif ch==4:
search_record()
elif ch==5:
display_record()
else:
print("Exiting")
break
'''Program 20: Write a menu-driven program to perform all the basic operations using dictionary on
student binary file such as inserting, reading, updating, searching and deleting a record.
(Note : Each student record contains {Rollno, name , marks}'''

import pickle
def Write():
stu={}
stufile=open("sto.dat",'ab')
ans='y'
while ans=='y':
print("Enter detail :")
rno=int(input("Enter the roll No"))
name=input("Enter the name")
marks=int(input("Enter the marks"))
stu['Roll']=rno
stu['Name']=name
stu['Marks']=marks
pickle.dump(stu,stufile)
ans=input("Do you want to continue(y/n)?")
stufile.close()
def Display():
stu={}
stufile=open("sto.dat",'rb')
try:
print("File stores these records")
while True:
stu=pickle.load(stufile)
print(stu)
except EOFError:
stufile.close()
def Search():
stu={}
found=False
stufile=open("sto.dat",'rb')
r=int(input("Enter the roll number to be searched"))
try:
print("Searching in the file")
while True:
stu=pickle.load(stufile)
if stu['Roll']==r:
print(stu)
found=True
except EOFError:
if found==False:
print("No such records found in the file")
else:
print("Search Successful.")
stufile.close()
def Update():
stu={}
found=False
c=0
stufile=open("sto.dat",'r+b')
try:
while True:
rpos=stufile.tell()
stu=pickle.load(stufile)
if stu['Marks']>80:
c=c+1
stu['Marks']+=2
stufile.seek(rpos)
pickle.dump(stu,stufile)
found=True
except EOFError:
if found==False:
print("Sorry, no matching record found")
else:
print(c,"Record(s) successfully updated")
stufile.close()
def Delete():
import os
stu={}
stufile=open("sto.dat",'rb')
stufile1=open("sto1.dat",'wb')
f=0
r=int(input("Enter the roll number whose marks has to be deleted"))
try:
while True:
stu=pickle.load(stufile)
if stu['Roll']!=r:
pickle.dump(stu,stufile1)
if stu['Roll']==r:
f=1
except EOFError:
if f==1:
print("Record Deleted")
else:
print("Record not found")
stufile.close()
stufile1.close()
os.remove("sto.dat")
os.rename("sto1.dat","sto.dat")
while True:
print("1:Enter record")
print("2:Update record")
print("3:Delete Record")
print("4:Search Record")
print("5:Display Record")
ch=int(input("Enter your choice"))
if ch==1:
Write()
elif ch==2:
Update()
elif ch==3:
Delete()
elif ch==4:
Search()
elif ch==5:
Display()
else:
print("Exiting")
break

OUTPUT:

You might also like