You are on page 1of 8

TEXT FILE OPERATIONS

#File copy except the letter 'a' using line by line #Count Vowels , consonant, special char , digits etc.,
f1=open('note.txt') f1=open('note.txt')
f2=open('B.txt','w') f2=open('B.txt','w')
d=f1.readline() d=f1.read() #d=input('Enter any String :')
while d!='': Vow=['a','e','i','o','u','A','E','I','O','U']
if 'a' not in d: V=C=U=L=O=0
f2.write(d) for i in d:
d=f1.readline() if i.isalpha():
#print('*',end='') if i.isupper():
f2.close() U+=1
f1.close() else:
print('File copied') L+=1
if i in Vow:
#convert lowercase to uppercase and vice-versa V+=1
f1=open('note.txt') else:
f2=open('B.txt','w') C+=1
d=f1.read() else:
#d=input('Any String :') O+=1
for i in d: print("Number of Vowels : ",V)
if i.isupper(): print("Number of Consonants : ",C)
x=i.lower() print("Number of Uppercases : ",U)
else: print("Number of Lowercases : ",L)
x=i.upper() print("Number of Others : ",O)
f2.write(x)
#print(x,end='') f2.close()
f2.close() f1.close()
f1.close() print('File copied')
print('File copied')
1
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI


#Except a particular letter 'H' or 'h' #Count number of lines/characters/words
f1=open('note.txt') f1=open('note.txt')
f2=open('B.txt','w') def dispwords():
d=f1.read() d=f1.readline()
for i in d: L=C=W=0
if i !='H' and i!='h': while d!='':
f2.write(i) L+=1
f2.close() C+=len(d)
f1.close() Words=d.split()
print('File copied') for i in Words:
#Counting the words 'the' W+=1
f1=open('note.txt') d=f1.readline()
f2=open('B.txt','w') print('Total number of Lines : ',L)
d=f1.readline() print('Total number of Characters : ',C)
cnt=0 print('Total number of Words : ',W)
while d!='': dispwords()
if 'the' in d: f1.close()
x=d.count('the') #Display the words started with uppercase letters
cnt+=x f1=open('note.txt')
print('The word appears ',x,' times in ',d) def dispwords():
else: d=f1.readline()
f2.write(d) while d!='':
d=f1.readline() Words=d.split()
print(cnt) for word in Words:
f2.close() if word[0].isupper():
f1.close() print(word,end=' ')
print('File copied') d=f1.readline()
#Capitalize the First letter of each line dispwords()
f1=open('note.txt') f1.close()
f2=open('B.txt','w') #Display the file contents and number of digits
d=f1.readline() f1=open('note.txt')
while d!='': def disp():
if d[0].isalpha(): d=f1.read()
d=d[0].upper()+d[1:] digi=0
f2.write(d) for i in d:
d=f1.readline() if i.isdigit():
f2.close() digi+=1
f1.close() print('The content of the file is \n',d)
2
Page

print('File copied') print('Number of digits ',digi)


SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI
disp()
f1.close()
#Display number of lines and started with #Display the words which are end with 'n'
the letter A/B/C f1=open('note.txt')
f1=open('note.txt') def disp():
def disp(): d=f1.readline()
d=f1.readline() cnt=0
L=C=0 while d!='':
while d!='': Words=d.split()
L+=1 for word in Words:
if d[0].isalpha(): if word[-1]=='n':
if d[0].isupper(): cnt+=1
if d[0]=='A' or d[0]=='B' or d[0]=='C': print(word,end=' ')
C+=1 d=f1.readline()
d=f1.readline() print("\nTotal number of words end with 'n' is ",cnt)
print('Total number of Lines : ',L) disp()
print('Total number of words started with f1.close()
A/B/C is : ',C)
disp()
f1.close()

#Display the words which are less than 4 characters #Display the words which are end with 'n'
f1=open('note.txt') f1=open('note.txt')
def disp(): def disp():
d=f1.readline() d=f1.readlines()
while d!='': cnt=0
Words=d.split() for i in d:
for word in Words: Words=i.split()
if len(word)<4: for word in Words:
print(word,end=' ') if word[-1]=='n':
d=f1.readline() cnt+=1
disp() print(word,end=' ')
f1.close() print("\nTotal number of words end with 'n' is ",cnt)
disp()
f1.close()
3
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI


BINARY FILE OPERATION
#File Operations on BINARY File
import pickle
Sdet=[]

def AddRec(): #1-Adding a record def UpdateRec(): #3-Updating a record


f1=open('STUD.DAT','wb') Sdet=[]
sno=int(input('Enter Student Number ')) f1=open('STUD.DAT','rb')
sname=input('Enter Student Name ') while True:
smark=int(input('Enter Mark ')) try:
Sdet.append([sno,sname,smark]) Sdet=pickle.load(f1)
pickle.dump(Sdet,f1) #pickle.dump(value,filehandle) #Variable=pickle.load(FileHandle)
print("A record inserted") except EOFError:
f1.close() break
f1.close()
def SearchRec(): #2-Searching a record f2=open('STUD.DAT','wb')
Sdet=[] sno=int(input('Enter serial number to Update '))
f2=open('STUD.DAT','rb') Found=0
while True: for s in Sdet:
try: if s[0]==sno:
Sdet=pickle.load(f2) sname=input('Enter a new name ')
except EOFError: print('Before updation ')
break print(s)
sno=int(input('Enter serial number to Search ')) print('After updation ')
Found=0 s[1]=sname
for s in Sdet: print(s)
if s[0]==sno: Found=1
print('Name : ',s[1],'Mark : ',s[2]) break
Found=1 pickle.dump(Sdet,f2)
break if Found==0:
if Found==0: print('No record found...')
print('No record found...') f2.close()
f2.close()
4
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI


def DelRec(): #4-Deleting a record def ShowRec(): #5-Displaying records
Sdet=[] Sdet=[]
f1=open('STUD.DAT','rb') f2=open('STUD.DAT','rb')
while True: while True:
try: try:
Sdet=pickle.load(f1) Sdet=pickle.load(f2)
except EOFError: except EOFError:
break break
f1.close() print(Sdet)
f2=open('STUD.DAT','wb') f2.close()
sno=int(input('Enter serial number to delete '))
Found=0 while True:
cnt=0 opt=int(input('1-Add 2-Search 3-Update 4-Delete
for s in Sdet: 5-Show 6-Exit'))
if s[0]==sno: if opt==1:
print('Before deletion ') AddRec()
print(Sdet) elif opt==2:
print('After deletion ') SearchRec()
Sdet.pop(cnt) elif opt==3:
print(Sdet) UpdateRec()
Found=1 elif opt==4:
break DelRec()
cnt+=1 elif opt==5:
pickle.dump(Sdet,f2) ShowRec()
if Found==0: elif opt==6:
print('No record found...') break
f2.close() else:
print('Invalid input ')
print('File operation is done...')
5
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI


CSV FILE OPERATION
#File Operations on CSV File
import csv

def AddRec(): #1-Adding a record def ShowRec(): #3-Displaying records


with open('MYCSVFILE.CSV','a') as f1: f1=open('MYCSVFILE.CSV','r')
W=csv.writer(f1,delimiter=',') R=csv.reader(f1,delimiter=',')
sno=int(input('Enter Student Number ')) Found=0
sname=input('Enter Student Name ') for row in R:
smark=int(input('Enter Mark ')) if len(row)!=0:
W.writerow((sno,sname,smark)) print(row)
print('Record inserted...') Found=1
if Found==0:
def SearchRec(): #2-Searching a record print('No record found...')
f1=open('MYCSVFILE.CSV','r') f1.close()
R=csv.reader(f1,delimiter=',')
sno=int(input('Enter serial number to Search ')) while True:
Found=0 opt=int(input('1-Add 2-Search 3-Show 4-Exit'))
for row in R: if opt==1:
if len(row)!=0: AddRec()
if int(row[0])==sno: elif opt==2:
print('Name : ',row[1],'Mark : ',row[2]) SearchRec()
Found=1 elif opt==3:
break ShowRec()
if Found==0: elif opt==4:
print('No record found...') break
f1.close() else:
print('Invalid input ')
print('File operation is done...')
6
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI


#Interface Python with MySQL : Employee Details
import mysql.connector as mcr
cn = mcr.connect(host='localhost',user='root',password='admin')
#cn = mcr.connect(host='127.0.0.1',user='root',password="admin",database='company')
cr = cn.cursor()
cr.execute('create database if not exists company')
cr.execute("use company")
cr.execute("create table if not exists employee(empno int, name varchar(20), dept varchar(20),salary int)")
print("Table Created Successfully...")
cn.commit()
while True:
opt=int(input("1. ADD RECORD 2. UPDATE RECORD 3.DELETE RECORD 4. SEARCH 5.DISPLAY 6.EXIT : "))
if opt==1: #INSERTING A RECORD
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
#query="insert into employee values(%s,'%s','%s',%s)"%(e,n,d,s)
cr.execute(query)
cn.commit()
print("A RECORD INSERTED...")
elif opt==2: #UPDATING A RECORD
e=int(input("Enter employee number to be updated "))
s=int(input("Enter salary to be updated "))
query="update employee set salary={} where empno={}".format(s,e)
#query="update employee set salary=%s where empno=%s"%(s,e)
cr.execute(query)
print("A Record Updated ")
cn.commit()
elif opt==3: #DELETING A RECORD
e=int(input("Enter employee number to be deleted"))
query="delete from employee where empno={}".format(e)
cr.execute(query)
print("Record(s) Deleted ")
cn.commit()
7

elif opt==4: #SEARCHING A RECORD


Page

e=int(input("Enter employee number to be searched"))


SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI
query="select * from employee where empno={}".format(e)
#query="select * from employee where empno=%s"%(e)
cr.execute(query)
result = cr.fetchall()
if cr.rowcount==0:
print("Record not found")
else:
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
cn.commit()
elif opt==5: #DISPLAYING RECORDS
query="select * from employee"
cr.execute(query)
result = cr.fetchall()
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
cn.commit()
elif opt==6: #CLOSING DATABASE
cn.close()
print("File closed successfully...")
break
else:
print("Invalid OPtion...")

8
Page

SHUNMUGA SUNDARAM S. M.E/CSE, A.M.I.E, MCP, M.I.S.T.E, M.IAEnGG – 9994548619 - TIRUNELVELI

You might also like