File Operation

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

FILE OPERATION

fn=input("Enter file name: ")


f=open(fn,"w+")
if f:
print("File Opened Successfully")
n=int(input("Enter Number of lines to be write into File: "))
print("Enter the content")
for i in range(n):
f.write(input())
f.close()
f=open(fn,"r")
print("Content of file is: ")
if f.mode=='r':
content=f.read()
print(content)
else:
print("File open Failed")
OUTPUT
Enter file name: Sri.txt
File Opened Successfully
Enter Number of lines to be write into File: 3
Enter the content
ctrl
alt
delete
Content of file is:
Ctrl alt delete
BUILT IN FUNCTIONS FOR NUMERIC TYPE

n=float(input("Enter the Number:"))


print("Floating Value of number is : ",n)
print("Integer Value of number is : ",int(n))
print("Absolute Value of number is : ",abs(n))
print("ASCII Value : ",ascii(n))
print("Binary Value : ",bin(int(n)))
print("Boolean Value : ",bool(n))
print("Character Value : ",chr(int(n)))
print("Hexa Decimal Value : ",hex(int(n)))
print("Hexa Octal Value : ",oct(int(n)))
print("ID of Value : ",id(n))
print("Output of Format Method")
print("Float Point Value: ",format(n, "f"))
print("Fill Value: ",format(int(n), "*>+10,d"))
print("Float Number with decimal Precision: ",format(n, "^-09.3f"))
print("Power value : ",pow(n,3))
print("Round Value : ",round(n))
OUTPUT

Enter the Number:4


Floating Value of number is : 4.0
Integer Value of number is : 4
Absolute Value of number is : 4.0
ASCII Value : 4.0
Binary Value : 0b100
Boolean Value : True
Character Value :
Hexa Decimal Value : 0x4
Hexa Octal Value : 0o4
ID of Value : 2729849699352
Output of Format Method
Float Point Value: 4.000000
Fill Value: ********+4
Float Number with decimal Precision: 004.00000
Power value : 64.0
Round Value : 4
TEST FOR IDENTIFIER VALIDITY

import re
a=input("Enter the Mail ID: ")
mails=['@gmail.com','@hotmail.com','@stc.ac.in','yahoomail.com']
if a[0].isalpha() and a[1].isalpha():
for i in range(len(mails)):
if mails[i] in a:
flag=1
break
else:
flag=0
if flag==1:
print("Valid Mail id")
else:
print("Invalid Mail id")
password=input("Enter password: ")
flag=0
while True:
if len(password)<8:
flag=-1
break
elif not re.search("[a-z]",password):
flag=-1
break
elif not re.search("[A-Z]",password):
flag=-1
break
elif not re.search("[0-9]",password):
flag=-1
break
elif not re.search("[@_*&]",password):
flag=-1
break
else:
flag=0
break
if flag==-1:
print("Valid password")
else:
print("Invalid password")
OUTPUT
Enter the Mail ID: [email protected]
Valid Mail id
Enter password: sundar
Valid password
STANDARD BUILD IN FUNCTIONS

i=int(input("Enter a number :"))


print("Absolute value of",i,"is:",abs(i))
fl=float(input("Enter a floating number"))
print("Absolute value of",fl,"is:",abs(fl))
l=[1,3,4,5]
print("All value of l",all(l))
print("Any value of l",any(l))
print("All values false")
l=[0,False]
print("All value of l",all(l))
print("Any value of l",any(l))
print("One true value")
l=[0,False,5]
print("All value of l",all(l))
print("Any value of l",any(l))
print("Empty iteratable")
l=[]
print("All value of l",all(l))
print("Any value of l",any(l))
txt="Welcome to Python"
print("The ASCII value",ascii(txt))
print("The length is",len(txt))
number=int(input("Enter a number :"))
print("The binary equivalent is",bin(number))
print("The hexa decimal equivalent is",hex(number))
print("The octal equivalent is",oct(number))
bl=input("Enter a value:")
print("The boolean equivalent is",bool(bl))
size=5
arr=bytearray(size)
print("Byte array is",arr)
rlist=[1,2,3,4,5]
arr=bytearray(rlist)
print("Byte array is",arr)
ch=int(input("Enter a number:"))
print("The character equivalent is",chr(ch))
OUTPUT

Enter a number: 500


Absolute value of 500 is: 500
Enter a floating number500.99
Absolute value of 500.99 is: 500.99
All value of l True
Any value of l True
All values false
All value of l False
Any value of l False
One true value
All value of l False
Any value of l True
Empty iteratable
All value of l True
Any value of l False
The ASCII value 'Welcome to Python'
The length is 17
Enter a number: 7
The binary equivalent is 0b111
The hexa decimal equivalent is 0x7
The octal equivalent is 0o7
Enter a value: 5
The boolean equivalent is True
Byte array is bytearray(b'\x00\x00\x00\x00\x00')
Byte array is bytearray(b'\x01\x02\x03\x04\x05')
Enter a number: 77
The character equivalent is M
LIST OPERATIONS

n=int(input("Enter the number of elements into the list: "))


l=list()
print("Enter the elements: ")
for i in range(n):
l.append(input())
print("Elements of list are",l)
index=int(input("Enter the index value of list: "))
print(l[index])
print("Slice operation")
st=int(input("Enter the starting index: "))
end=int(input("Enter the number of elements to be sliced: "))
print("Slice value is:",l[st:end])
print("Change operation")
n=int(input("Enter the index of elements to be changed: "))
val=int(input("Enter the value to be changed: "))
l[n]=val
print("Elements of list are",l)
l[1:3]=[6,7]
print("Elements of list are",l)
l2=[1,3,4]
print("Adding of two list is:",l+l2)
print("Repeat operation",l2*3)
print("Extend operation:")
l2.extend([12,13,14])
print(l2)
print("Length of list is",len(l2))
print("Minimum element of list is",min(l2))
print("Maximum element of list is",max(l2))
print("Pop element of list is",l2.pop())
l2.sort()
print("Sorted elements of list",l2)
OUTPUT

Enter the number of elements into the list: 3


Enter the elements:
5
57
58
Elements of list are ['5', '57', '58']
Enter the index value of list: 0
5
Slice operation
Enter the starting index: 0
Enter the number of elements to be sliced: 1
Slice value is: ['5']
Change operation
Enter the index of elements to be changed: 2
Enter the value to be changed: 100
Elements of list are ['5', '57', 100]
Elements of list are ['5', 6, 7]
Adding of two list is: ['5', 6, 7, 1, 3, 4]
Repeat operation [1, 3, 4, 1, 3, 4, 1, 3, 4]
Extend operation:
[1, 3, 4, 12, 13, 14]
Length of list is 6
Minimum element of list is 1
Maximum element of list is 14
Pop element of list is 14
Sorted elements of list [1, 3, 4, 12, 13]
STRING TYPE FUNCTION

a=input("Enter a string: ")


print("Capitalize method:",a.capitalize())
print("Isalnum method:",a.isalnum())
print("Isalpha method:",a.isalpha())
print("Isdigit method:",a.isdigit())
print("Islower method:",a.islower())
print("Isupper method:",a.isupper())
print("Isspace method:",a.isspace())
print("Len method:",len(a))
print("Lower method:",a.lower())
print("Upper method:",a.upper())
print("Swapcase method:",a.swapcase())
print("Istitle method:",a.istitle())
print("Isdecimal method:",a.isdecimal())
sub=input("Enter a substring from the above string: ")
print("count method:",a.count(sub,5,50))
print("Endswith method:",a.endswith(sub,3,14))
print("Find method:",a.find(sub,3))
OUTPUT
Enter a string: Whatsapp
Capitalize method: Whatsapp
Isalnum method: True
Isalpha method: True
Isdigit method: False
Islower method: False
Isupper method: False
Isspace method: False
Len method: 8
Lower method: whatsapp
Upper method: WHATSAPP
Swapcase method: wHATSAPP
Istitle method: True
Isdecimal method: False
Enter a substring from the above string: s
count method: 0
Endswith method: False
Find method: 4
DICTIONARY TYPE METHODS

dsm=dict()
print("Empty Dictionary:",dsm)
print("Type Methd:",type(dsm))
n=int(input("Enter the no of elements into the dictionary:"))
print("Enter the elements:")
for i in range(n):
print("Enter the key:")
ky=input()
print("Enter the value:")
val=input()
ne={ky:val}
dsm.update(ne)
print("The Dictionary:",dsm)
va=input("Enter the key value of Dictionary to find: ")
print("Key values of Dictionary is:",dsm.get(va))
print("The Items of Dictionary:",dsm.items())
print("The keys of dictionary:",dsm.keys())
print("The values of Dictionary:",dsm.values())
p=input("Enter the key value for pop: ")
print("The values of pop element in Dictionary:",dsm.pop(p))
print("The Dictionary after pop:",dsm)
ndsm=dsm.copy()
print("Copy of Dictionary:",ndsm)
print("Length of Dictionary:",len(dsm))
print("Maximum of Dictionary:",max(dsm))
print("Minimum of Dictionary:",min(dsm))
dsm.clear()
print("Dictionary After clear method:",dsm)
OUTPUT
Empty Dictionary: {}
Type Methd: <class 'dict'>
Enter the no of elements into the dictionary:3
Enter the elements:
Enter the key:
Name:
Enter the value:
Sri
Enter the key:
Age:
Enter the value:
20
Enter the key:
Gender:
Enter the value:
Male
The Dictionary: {'Name:': 'Sri', 'Age:': '20', 'Gender:': 'Male'}
Enter the key value of Dictionary to find: Gender:
Key values of Dictionary is: Male
The Items of Dictionary: dict_items([('Name:', 'Sri'), ('Age:', '20'), ('Gender:', 'Male')])
The keys of dictionary: dict_keys(['Name:', 'Age:', 'Gender:'])
The values of Dictionary: dict_values(['Sri', '20', 'Male'])
Enter the key value for pop: Age:
The values of pop element in Dictionary: 20
The Dictionary after pop: {'Name:': 'Sri', 'Gender:': 'Male'}
Copy of Dictionary: {'Name:': 'Sri', 'Gender:': 'Male'}
Length of Dictionary: 2
Maximum of Dictionary: Name:
Minimum of Dictionary: Gender:
Dictionary After clear method: {}
EXCEPTION HANDLING
try:
b=input("Enter a value: ")
print("The enter value is",b)
r=1/int(b)
except:
print("OOPS!",sys.exe_info()[0],"occured")
print("Next Entry")
print()
print("The reciprocal of",b,"is",r)
OUTPUT
Enter a value: 5
The enter value is 5
The reciprocal of 5 is 0.2
CREATING EXCEPTION

class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
acno=int(input("Enter a Account number:"))
name=input("Enter Name:")
bal=float(input("Enter balance:"))
while True:
try:
wid=float(input("Enter the Withdrawal amount:"))
if wid<0:
raise ValueTooSmallError
elif wid>bal:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("Amount Withdrawal could not be negative. Please try again")
print()
except ValueTooLargeError:
print("Withdrawal amount greater than available balance.Try again")
print("Amount withdrawal successful.Current balance is",bal-wid)
OUTPUT
Enter a Account number:5896478987456321
Enter Name:Sri
Enter balance:87000
Enter the Withdrawal amount:-500
Amount Withdrawal could not be negative. Please try again

Enter the Withdrawal amount:6000


Amount withdrawal successful.Current balance is 81000.0
INHERITANCE
class person:
def __init__(self):
self.name=input("Name:")
self.age=input("Age:")
self.gender=input("Gender:")
def display(self):
print("\nName:",self.name)
print("Age:",self.age)
print("Gender",self.gender)
class marks:
def __init__(self):
self.stuclass=input("class:")
print("Enter the marks of respective subjects:")
self.py=int(input("Python:"))
self.ad=int(input("Android:"))
self.e1=int(input("Elective1:"))
self.e2=int(input("Elective2:"))
def display(self):
print("Class:",self.stuclass)
print("python:",self.py)
print("Android:",self.ad)
print("Elective1:",self.e1)
print("Elective2:",self.e2)
print("Average marks:",(self.py+self.ad+self.e1+self.e2)/4)
class student(person, marks):
def __init__(self):
person.__init__(self)
marks.__init__(self)
def result(self):
person.display(self)
marks.display(self)
stu1 = student()
stu2 = student()
stu1.result()
stu2.result()
OUTPUT
Name:Sri
Age:20
Gender:Male
class:III Bsc IT
Enter the marks of respective subjects:
Python:78
Android:87
Elective1:89
Elective2:78
Name:Sri
Age:20
Gender:Male
class:III Bsc IT
Enter the marks of respective subjects:
Python:96
Android:87
Elective1:88
Elective2:98

Name: Sri
Age: 20
Gender Male
Class: III Bsc IT
python: 78
Android: 87
Elective1: 89
Elective2: 78
Average marks: 83.0

Name: Sri
Age: 20
Gender Male
Class: III Bsc IT
python: 96
Android: 87
Elective1: 88
Elective2: 98
Average marks: 92.25
THREAD AND LOCKS
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
threadLock.acquire()
print_time(self.name, self.counter, 3)
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread3 = myThread(3, "Thread-2", 2)
thread1.start()
thread2.start()
thread3.start()
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)
for t in threads:
t.join()
print ("Exiting Main Thread")
OUTPUT
Starting Thread-1Starting Thread-2Starting Thread-2

Thread-1: Sun Mar 31 22:45:27 2019


Thread-1: Sun Mar 31 22:45:28 2019
Thread-1: Sun Mar 31 22:45:29 2019
Thread-2: Sun Mar 31 22:45:31 2019
Thread-2: Sun Mar 31 22:45:33 2019
Thread-2: Sun Mar 31 22:45:35 2019
Thread-2: Sun Mar 31 22:45:37 2019
Thread-2: Sun Mar 31 22:45:39 2019
Thread-2: Sun Mar 31 22:45:41 2019
Exiting Main Thread
GUI PROGRAM

from tkinter import *


def red():
root.configure(background="red")
root.geometry("400*400")
root.title("Red")
def green():
root.configure(background="green")
root.geometry("500*500")
root.title("Green")
def blue():
root.configure(background="blue")
root.geometry("600*600")
root.title("Blue")
root=Tk()
frame=Frame(root)
frame.pack()
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM)
redbutton=Button(frame,text='Red',fg='red',command=red)
redbutton.pack(side=LEFT)
greenbutton=Button(frame,text='Green',fg='green',command=green)
greenbutton.pack(side=LEFT)
bluebutton=Button(frame,text='Blue',fg='blue',command=blue)
bluebutton.pack(side=LEFT)
root.geometry("300*300")
root.title("color")
root.mainloop()
OUTPUT
CGI PROGRAM
PYTHON:
#!C:/Users/Sri/AppData/Local/Programs/Python/Python37/python.exe -u
import cgi, cgitb
form = cgi.FieldStorage()
Name= form.getvalue('textnames')
FName= form.getvalue('fathername')
PAddress=form.getvalue('paddress')
Sex=form.getvalue('sex')
City=form.getvalue('City')
Course=form.getvalue('Course')
Dist=form.getvalue('District')
State=form.getvalue('State')
PinCode=form.getvalue('pincode')
EmailId=form.getvalue('emailid')
MobileNo=form.getvalue('mobileno')
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Student Information System</title>")
print("</head>")
print("<body>")
print("<table cellpadding='2' width='20%' bgcolor='99FFFF' align='center' cellspacing=2'>")
print("<tr><td colspan=2><center><font size=4><b>Student Registration
Details</b></font></center></td></tr>")
print("<tr><td>Name</td><td>",Name,"</td></tr>")
print("<tr><td>Father Name</td><td>",FName,"</td></tr>")
print("<tr><td>Postal Address</td><td>",PAddress,"</td></tr>")
print("<tr><td>Sex</td><td>",Sex,"</td></tr>")
print("<tr><td>City</td><td>",City,"</td></tr>")
print("<tr><td>Course</td><td>",Course,"</td></tr>")
print("<tr><td>District</td><td>",Dist,"</td></tr>")
print("<tr><td>State</td><td>",State,"</td></tr>")
print("<tr><td>PinCode</td><td>",PinCode,"</td></tr>")
print("<tr><td>E-Mail ID</td><td>",EmailId,"</td></tr>")
print("<tr><td>Mobile No</td><td>",MobileNo,"</td></tr>")
print("</table>")
print("</body>")
print("</html>")
HTML :
<html>
<head>
<title>Student Information System</title>
</head><body>
<form action="SInformation.py" name="StudentRegistration" method="post">
<table cellpadding="2" width="20%" bgcolor="99FFFF" align="center"
cellspacing="2">
<tr><td colspan=2>
<center><font size=4><b>Student Registration Form</b></font></center>
</td></tr>
<tr><td>Name</td>
<td><input type=text name=textnames id="textname" size="30"></td>
</tr>
<tr><td>Father Name</td>
<td><input type="text" name="fathername" id="fathername"
size="30"></td>
</tr>
<tr><td>Postal Address</td>
<td><input type="text" name="paddress" id="paddress" size="30"></td>
</tr><tr>
<td>Sex</td>
<td><input type="radio" name="sex" value="male" size="10">Male
<input type="radio" name="sex" value="Female" size="10">Female</td>
</tr>
<tr><td>City</td>
<td><select name="City">
<option value="-1" selected>select..</option>
<option value="Pollachi">Pollachi</option>
<option value="Coimbatore">Coimbatore</option>
<option value="Udumalpet">Udumalpet</option>
<option value="Palani">Palani</option>
</select></td></tr>
<tr>
<td>Course</td>
<td><select name="Course">
<option value="-1" selected>select..</option>
<option value="B.Sc IT">B.Sc IT</option>
<option value="MCA">MCA</option>
<option value="MBA">MBA</option>
<option value="BCA">BCA</option>
</select></td></tr>
<tr>
<td>District</td>
<td><select name="District">
<option value="-1" selected>select..</option>
<option value="Coimbatore">Coimbatore</option>
<option value="Thiruppur">Thiruppur</option>
</select></td></tr>
<tr><td>State</td>
<td><select Name="State">
<option value="-1" selected>select..</option>
<option value="Tamil Nadu">Tamil Nadu</option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Kerala">Kerala</option>
<option value="Karnataka">Karnataka</option>
</select></td>
</tr>
<tr><td>PinCode</td>
<td><input type="text" name="pincode" id="pincode" size="30"></td>
</tr>
<tr><td>EmailId</td>
<td><input type="text" name="emailid" id="emailid" size="30"></td>
</tr>
<tr>
<td>MobileNo</td>
<td><input type="text" name="mobileno" id="mobileno" size="30"></td>
</tr>
<tr>
<td><input type="reset"></td>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
OUTPUT
DATABASE CONNECTIVITY WITH PYTHON

import pymysql
db = pymysql.connect(host='localhost', user='root', passwd='', db='student')
cursor = db.cursor()
ch='Y'
while(ch=='Y'):
print("\n\t\tVarious Operation\n\t1.Insert\n\t2.Delete\n\t3.Update\n\t4.Display")
op=int(input("Enter Your Choice"))
if op==1:
print("\n\t\tInsert Operation")
name = input("Name: ")
age = int(input("Age: "))
gender = input("Gender: ")
stuClass = input("Class: ")
print("Enter the marks of the respective subjects")
py = int(input("Python: "))
ad = int(input("Android: "))
e1 = int(input("Elective 1: "))
e2 = int(input("Elective 2: "))
sql = "INSERT INTO student(name,age,gender,Class,py,ad,e1,e2)VALUES
('%s','%d','%s','%s','%d','%d','%d','%d')" % (name,age,gender,stuClass,py,ad,e1,e2)
try:
cursor.execute(sql)
db.commit()
print("\n\t\t****Record Inserted Successfully***")
except:
db.rollback()
elif op==2:
print("\n\t\tDelete Operation")
name = input("Enter the Name to be Deleted: ")
sql = "DELETE FROM student where name=('%s')" % (name)
try:
cursor.execute(sql)
db.commit()
print("\n\t\t****Record Deleted Successfully***")
except:
db.rollback()
elif op==3:
print("\n\t\tUpdate Operation")
name = input("Enter the Name to be Updated: ")
print("Details for Updated")
age = int(input("Age: "))
gender = input("Gender: ")
stuClass = input("Class: ")
print("Enter the marks of the respective subjects")
py = int(input("Python: "))
ad = int(input("Android: "))
e1 = int(input("Elective 1: "))
e2 = int(input("Elective 2: "))
sql = "UPDATE student SET
age=('%d'),gender=('%s'),Class=('%s'),py=('%d'),ad=('%d'),e1=('%d'),e2=('%d') where
name=('%s')" % (age,gender,stuClass,py,ad,e1,e2,name)
try:
cursor.execute(sql)
db.commit()
print("\n\t\t****Record Updated Successfully***")
except:
db.rollback()
elif op==4:
print("\n\t\tDisplay Operation")
print("Details Student")
sql = "SELECT * FROM student"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print("Name: ",row[0])
print("Age: ",row[1])
print("Gender: ",row[2])
print("Class: ",row[3])
print("\tMarks of the respective subjects")
print("Python: ",row[4])
print("Android: ",row[5])
print("Elective 1: ",row[6])
print("Elective 2: ",row[7])
else:
print("\n\tWrong Operation")
ch=(input("Do you have any other transaction(Y/N): ")).capitalize()
db.close()
OUTPUT

Various Operation
1.Insert
2.Delete
3.Update
4.Display
Enter Your Choice1

Insert Operation
Name: Sri
Age: 19
Gender: Male
Class: III BSC IT
Enter the marks of the respective subjects
Python: 48
Android: 47
Elective 1: 49
Elective 2: 46

****Record Inserted Successfully***


Do you have any other transaction(Y/N): y

Various Operation
1.Insert
2.Delete
3.Update
4.Display
Enter Your Choice3

Update Operation
Enter the Name to be Updated: Sri
Details for Updated
Age: 20
Gender: Male
Class: III BSC IT
Enter the marks of the respective subjects
Python: 47
Android: 40
Elective 1: 43
Elective 2: 41

****Record Updated Successfully***


Do you have any other transaction(Y/N): y
Various Operation
1.Insert
2.Delete
3.Update
4.Display
Enter Your Choice4

Display Operation
Details Student
Name: Sri
Age: 20
Gender: Male
Class: III BSC IT
Marks of the respective subjects
Python: 47
Android: 40
Elective 1: 43
Elective 2: 41
Do you have any other transaction(Y/N): y

Various Operation
1.Insert
2.Delete
3.Update
4.Display
Enter Your Choice2

Delete Operation
Enter the Name to be Deleted: Sri

****Record Deleted Successfully***


Do you have any other transaction(Y/N): n

You might also like