Chapter 12: Files

Example 1, Page Number : FLS-7

In [1]:
fp = open("SAMPLE.TXT","w")

print "\nType the text press enter key at end.\n\n"

ch = raw_input("")
fp.write(ch)

fp.close()
Type the text press enter key at end.


Computer Programming in C language is widely used for Science and Engineering applications.

Example 2, Page Number : FLS-8

In [8]:
import sys

count = 0 

fp = open("SAMPLE.TXT","r")

print "\nThe content of the text file is : \n\n"

ch = fp.read()

for i in ch:
    sys.stdout.write("%c"%(i))
    if i.upper() == 'A' or i.upper() == 'E' or i.upper() == 'I' or i.upper() == 'O' or i.upper() == 'U':
        count = count + 1
        
print "\nNumber of vowels present = ",count
fp.close()
The content of the text file is : 


Computer Programming in C language is widely used for Science and Engineering applications.
Number of vowels present =  31

Example 3, Page Number : FLS-10

In [6]:
fp = open("STUDENT.DAT","w")

n = int(raw_input("\nHow many students ? "))

for i in range(0,n):
    rno = int(raw_input("\nStudent roll no., name, total ? "))
    sname = raw_input("")
    tot = int(raw_input(""))
    fp.write("%d %s %d\n"%(rno,sname,tot))
    
fp.close()
How many students ? 3

Student roll no., name, total ? 101
ARUN
78

Student roll no., name, total ? 102
DEEPAK
72

Student roll no., name, total ? 103
SUSHMITHA
86

Example 4, Page Number : FLS-11

In [11]:
fptr = open("STUDENT.DAT","r")

print "\n--------------------------------------------------------"
print "\n    Roll No        Name             Total               "
print "\n--------------------------------------------------------"

rno = 0
sname = ''
tot = 0

lines = fptr.readlines()

for line in lines:
    rno,sname,tot = line.split(' ')
    tot = int(tot)
    if tot >= 75:
        print "\n   ",rno,"\t",sname,"\t\t",tot
    
print "\n--------------------------------------------------------"
--------------------------------------------------------

    Roll No        Name             Total               

--------------------------------------------------------

    101 	ARUN 		78

    103 	SUSHMITHA 		86

--------------------------------------------------------

Example 5, Page Number : FLS-12

In [23]:
ch = 'y'

fp = open("STUDENT.DAT","a")

while ch.upper() == 'Y':
    rno = int(raw_input("\nStudent roll no., name, total ? "))
    sname = raw_input("")
    tot = int(raw_input(""))
    fp.write("%d %s %d\n"%(rno,sname,tot))
    print "\nPress y - to add more records"
    print "\n       any other key to stop."
    ch = raw_input("")
    
print "\n-------------------------------------------------------"
print "\n     Roll No.         Name              Total"
print "\n-------------------------------------------------------"

rno = 0
sname = ''
tot = 0

fp.close()
fp = open("STUDENT.DAT","r")

lines = fp.readlines()

for line in lines:
    rno,sname,tot = line.split(' ')
    print "\n   ",rno,"\t\t",sname,"\t\t",tot
    
print "\n--------------------------------------------------------"
Student roll no., name, total ? 104
RAHUL
67

Press y - to add more records

       any other key to stop.
N

-------------------------------------------------------

     Roll No.         Name              Total

-------------------------------------------------------

    101 		ARUN 		78


    102 		DEEPAK 		72


    103 		SUSHMITHA 		86


    104 		RAHUL 		67


--------------------------------------------------------

Example 6, Page Number : FLS-14

In [26]:
source_name = raw_input("\nEnter the source file name : ")

source_fptr = open(source_name,"r")

target_name = raw_input("\nEnter the target file name : ")
target_fptr = open(target_name,"w+")

if source_fptr == 0:
    print "\nNo content/source file !!!"
    print "\n   press any key..."
else:
    while True:
        ch = source_fptr.read(1)
        if not ch:
            break
        target_fptr.write("%c"%(ch))
        
target_fptr.close()
target_fptr = open(target_name,"r")

print "\nThe contents of the target file are"
print "\n---------------------------------------\n"
lines = target_fptr.readlines()

for line in lines:
    print line
    
target_fptr.close()
source_fptr.close()
print "\n\n  Press any key..."
Enter the source file name : SAMPLE.TXT

Enter the target file name : SAMPLE.BAK

The contents of the target file are

---------------------------------------

Computer Programming in C language is widely used for Science and Engineering applications.


  Press any key...

Example 7, Page Number : FLS-15

In [11]:
ch = 'y'

while ch == 'y' or ch == 'Y':
    print "\n\t          MENU"
    print "\n\t-------------------------------------------"
    print "\n\tPress 1 to create data file"
    print "\n\t      2 to find smallest & largest integer"
    
    choice = int(raw_input("\n\n\tEnter your choice : "))
    
    if choice == 1:
        data_file = open("DATAFILE","w")
        n = int(raw_input("\nEnter data, enter 0 at end of reading\n"))
        while n != 0:
            data_file.write("%d\n"%(n))
            n = int(raw_input(""))
        data_file.close()
    else:
        if choice == 2:
            data_file = open("DATAFILE","r")
            n1 = data_file.readlines()
            n = n1[0]
            big = n
            small = n
            for n in n1:
                if n > big:
                    big = n 
                if n < small:
                    small = n
                
            data_file.close()
            print "\nLargest integer is ",big
            print "\nSmallest integer is ",small
        else:
            print "\nWrong choice !!!"       
    ch = raw_input("\n\nPress Y to continue, any other key to stop...")
    
	          MENU

	-------------------------------------------

	Press 1 to create data file

	      2 to find smallest & largest integer


	Enter your choice : 1

Enter data, enter 0 at end of reading
23
6
76
-56
876
52
0


Press Y to continue, any other key to stop...y

	          MENU

	-------------------------------------------

	Press 1 to create data file

	      2 to find smallest & largest integer


	Enter your choice : 2

Largest integer is  876


Smallest integer is  -56



Press Y to continue, any other key to stop...n

Example 8, Page Number : FLS-20

In [1]:
import os

class emp_record:
    eno = 0
    ename = ''
    bpay = 0.0
    
erec = emp_record()

def creatfile():
    choice = 'y'
    efile = open("EMPLOY.DAT","w")
    while choice.upper() == 'Y':
        erec.eno = int(raw_input("\nEnter the employee No."))
        erec.ename = raw_input("\nEmployee Name ?")
        erec.bpay = float(raw_input("\nBasic pay ?"))
        efile.write("%d %s %f\n"%(erec.eno,erec.ename,erec.bpay))
        print "\n  Press Y - to continue"
        print "\n            any other key to stop."
        choice = raw_input("")
    efile.close()
    
def readfile():
    eno = 0
    ename = ''
    bpay = 0.0
    efile = open("EMPLOY.DAT","r")
    print "\n----------------------------------------------------"
    print "\n    Emp.No.         Employee Name        Basic pay"
    print "\n----------------------------------------------------"
    lines = efile.readlines()
    
    for line in lines:
        eno,ename,bpay = line.split(' ')
        print "\n",eno,"\t",ename,"\t",bpay
    print "\n----------------------------------------------------"

def appendrec():
    choice = 'y'
    efile = open("EMPLOY.DAT","a")
    while choice.upper() == 'Y':
        erec.eno = int(raw_input("\nEnter the employee No. "))
        erec.ename = raw_input("\nEmployee Name ? ")
        erec.bpay = float(raw_input("\nBasic pay ?"))
        efile.write("%d %s %f\n"%(erec.eno,erec.ename,erec.bpay))
        print "\nPress Y - to continue"
        print "\n          any other key to stop."
        choice = raw_input("")
    efile.close()
    
def modirec():
    flag = 0
    eno = 0
    ename = ''
    bpay = 0.0
    efile = open("EMPLOY.DAT","r+")
    print "\nTo modify a record "
    print "\n------------------"
    temp = int(raw_input("\nEnter the Roll No."))
    lines = efile.readlines()
    for line in lines:
    #while True and flag == 0:
        eno,ename,bpay = line.split(' ')
        if eno == temp:
            print "\nExisting record details"
            print "\n",eno,"\t",ename,"\t",bpay
            print "\n\nEnter the modified details"
            print "\n------------------------------"
            erec.eno = int(raw_input("\nEnter the employee No. "))
            erec.ename = raw_input("\nEmployee Name ? ")
            erec.bpay = float(raw_input("\nBasic pay ?"))
            efile.write("%d %s %f\n"%(erec.eno,erec.ename,erec.bpay))
            flag = 1
            print "\nThe record has been modified!"
    efile.close()
    if flag == 0:
        print "\nThe given record is not present in the file!!!"
    print "\nPress any key to continue ..."
    
def deleterec():
    flag = 0
    eno = 0
    ename = ''
    bpay = 0.0
    efile = open("EMPLOY.DAT","r")
    tfile = open("TEMP.DAT","w")
    print "\nTo delete a record"
    print "\n------------------"
    temp = int(raw_input("\nEnter the Roll No."))
    while True:
        eno,ename,bpay = efile.readline().split(' ')
        if eno == temp:
            print "\nExisting record details"
            print "\n",eno,"\t",ename,"\t",bpay
            print "\n is deleted!!!"
            flag = 1
            tfile.write("%d %s %f\n"%(eno,ename,bpay))
    tfile.close()
    efile.close()
    os.remove("EMPLOY.DAT")
    os.rename("TEMP.DAT","EMPLOY.DAT")
    if flag == 0:
        print "\nThe given record is not present in the file!!!"
    print "\n\tpress any key to continue..."
        
n = 0
while n != 6:
    print "\n\tMain Menu"
    print "\n\t Press  1 - file creation"
    print "\n\t        2 - reading"
    print "\n\t        3 - appending"
    print "\n\t        4 - modify a record"
    print "\n\t        5 - delete a record"
    print "\n\t        6 - quit"
    n = int(raw_input("\n\nEnter your choice : "))
    
    if n == 1:
        creatfile()
    else:
        if n == 2:
            readfile()
        else:
            if n == 3:
                appendrec()
            else:
                if n == 4:
                    modirec()
                else:
                    if n == 5:
                        deleterec()
                        
            
	Main Menu

	 Press  1 - file creation

	        2 - reading

	        3 - appending

	        4 - modify a record

	        5 - delete a record

	        6 - quit


Enter your choice : 1

Enter the employee No.2101

Employee Name ?ARUN

Basic pay ?8500

  Press Y - to continue

            any other key to stop.
Y

Enter the employee No.2102

Employee Name ?DEEPAK

Basic pay ?8000

  Press Y - to continue

            any other key to stop.
N

	Main Menu

	 Press  1 - file creation

	        2 - reading

	        3 - appending

	        4 - modify a record

	        5 - delete a record

	        6 - quit


Enter your choice : 2

----------------------------------------------------

    Emp.No.         Employee Name        Basic pay

----------------------------------------------------

2101 	ARUN 	8500.000000


2102 	DEEPAK 	8000.000000


----------------------------------------------------

	Main Menu

	 Press  1 - file creation

	        2 - reading

	        3 - appending

	        4 - modify a record

	        5 - delete a record

	        6 - quit


Enter your choice : 3

Enter the employee No. 2103

Employee Name ? SUSHMITHA

Basic pay ?6400

Press Y - to continue

          any other key to stop.
Y

Enter the employee No. 2104

Employee Name ? ASHIKA

Basic pay ?6200

Press Y - to continue

          any other key to stop.
N

	Main Menu

	 Press  1 - file creation

	        2 - reading

	        3 - appending

	        4 - modify a record

	        5 - delete a record

	        6 - quit


Enter your choice : 4

To modify a record 

------------------

Enter the Roll No.2101

The given record is not present in the file!!!

Press any key to continue ...

	Main Menu

	 Press  1 - file creation

	        2 - reading

	        3 - appending

	        4 - modify a record

	        5 - delete a record

	        6 - quit


Enter your choice : 6
In [ ]: