CHAPTER 12:FILE INPUT/OUTPUT

EXAMPLE ON PAGE:391

In [8]:
 
fp=open('PR1.txt','r')                              #open the file for reading
ch=fp.readlines()                                   #ch will store all content of file
print "%s" % (' '.join(ch))                         #prints content of file
print "\n"
fp.close()
site:http://www.bzu.edu.pk/
 user:siteuser@localhost
 version:5.5.32-0ubuntu0.12.04.1
 db: bzu
 tables:
 username:web,webadmin,webadministrator23
 pass:71dc9f7af599450b23a3b5d54bc665c7,	49fa1a081c8d5c8dcfa05d730803251a,	*E8665C4049F515D836A3C8704D0543C6DA0FE96D


EXAMPLE ON PAGE:394

In [9]:
 
try:
    fp=open('yoyo.txt','r')
    for line in fin:
        print line
    fp.close()
except:
    print 'cannot open file'
cannot open file

EXAMPLE ON PAGE:395

In [10]:
 
nol=0
nom=0
nob=0
noc=0
fp=open('H4CK3R.txt','r')
while True:
    ch=fp.read(1)
    if not ch:
        break
    noc+=1
    if ch==' ':
        nob+=1
    if ch=='\n':
        nol+=1
    if ch=='\t':
        nom+=1
fp.close()
print "\n"
fp.close()
print "Number of characters=%d\n" % (noc)
print "Number of blanks=%d\n" % (nob)
print "Number of tabs=%d\n" % (nom)
print "Number of lines=%d\n" % (nol)

Number of characters=162

Number of blanks=21

Number of tabs=3

Number of lines=4

EXAMPLE ON PAGE:396-397

In [1]:
 
import sys
try:
    fs=open('H4CK3R.txt','r')
except:
    print "Cannot open file"
    sys.exit(1)
try:
    ft=open('python.txt','w')
except:
    print "Cannot open file"
    fs.close()
    sys.exit(2)
ch=fs.readlines()
ft.writelines(ch)
fs.close()
ft.close()
An exception has occurred, use %tb to see the full traceback.

SystemExit: 1
Cannot open file
To exit: use 'exit', 'quit', or Ctrl-D.

EXAMPLE ON PAGE:399

In [15]:
 
try:
    fp=open('POEM.txt','w')
except:
    print 'cannot open file'
print "\nEnter a few lines of text:\n"
s=' '
while (len(s)>0):
    s=raw_input()
    fp.writelines(s)
    fp.writelines("\n")
fp.close()
Enter a few lines of text:

Shining and bright,they are forever,
so true about diamonds,
more so of memories,
especially yours!

EXAMPLE ON PAGE:400

In [16]:
 
try:
    fp=open('POEM.txt','r')
except:
    print 'cannot open file'
s=fp.read(99)
print "%s" % (s)
print "\n"
fp.close()
Shining and bright,they are forever,
so true about diamonds,
more so of memories,
especially yours!


EXAMPLE ON PAGE:401-402

In [17]:
 
class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
another='Y'
e=emp()
try:
    fp=open('EMPLOYEE.txt','w')
except:
    print 'cannot open file'
while another=='Y':
    print "\nEnter name,age and basic salary:"
    e.name=raw_input()
    e.age=eval(raw_input())
    e.bs=eval(raw_input())
    ch="%s %d %f" % (e.name,e.age,e.bs)
    fp.writelines(ch)
    fp.writelines("\n")
    print "Add another record(Y/N)"
    another=raw_input()
fp.close()
Enter name,age and basic salary:
Sunil
34
1250.50
Add another record(Y/N)
Y

Enter name,age and basic salary:
Sameer
21
1300.50
Add another record(Y/N)
Y

Enter name,age and basic salary:
Rahul
34
1400.55
Add another record(Y/N)
n

EXAMPLE ON PAGE:403-404

In [18]:
 
class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
e=emp()
try:
    fp=open('EMPLOYEE.txt','r')                             # open the file for reading
except:
    print 'cannot open file'
for line in fp:                                                # iterate over each line
        e.name, e.age, e.bs = line.split()                     # split it by whitespace
        e.age = int(e.age)                                     # convert age from string to int
        e.bs = float(e.bs)                                     # convert bs from string to float
        print "%s %d %f\n" %(e.name, e.age, e.bs)
fp.close()
Sunil 34 1250.500000

Sameer 21 1300.500000

Rahul 34 1400.550000

EXAMPLE ON PAGE:404-405

In [2]:
 
import sys                                                 #for exit()
try:
    fs=open('H4CK3R.txt','rb')                             # open the file for reading
except:
    print 'cannot open file'
    sys.exit(1)
try:
    ft=open('python.txt','wb')                             # open the file for writing
except:
    print 'cannot open file'
    fs.close()
    sys.exit(2)
ch=fs.readlines()
ft.writelines(ch)
fs.close()
ft.close()
An exception has occurred, use %tb to see the full traceback.

SystemExit: 1
cannot open file
To exit: use 'exit', 'quit', or Ctrl-D.

EXAMPLE ON PAGE:407-408

In [21]:
 
class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
another='Y'
e=emp()
try:
    fp=open('EMP.txt','wb')                             # open the file for reading
except:
    print 'cannot open file' 
while another=='Y':
    print "\nEnter name,age and basic salary:"
    e.name=raw_input()
    e.age=eval(raw_input())
    e.bs=eval(raw_input())
    ch="%s %d %f" % (e.name,e.age,e.bs)
    fp.writelines(ch)
    print "Add another record (Y/N)"
    another=raw_input()
    if another=='Y':
        fp.writelines("\n")
fp.close()
Enter name,age and basic salary:
Suresh
24
1250.50
Add another record (Y/N)
Y

Enter name,age and basic salary:
Ranjan
21
1300.60
Add another record (Y/N)
Y

Enter name,age and basic salary:
Harish
28
1400.70
Add another record (Y/N)
N

EXAMPLE ON PAGE:409

In [22]:
 
class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
e=emp()
try:
    fp=open('EMP.txt','rb')
except:
    print "Cannot open file"
for line in fp:
    e.name, e.age, e.bs = line.split()                     # split it by whitespace
    e.age = int(e.age)                                     # convert age from string to int
    e.bs = float(e.bs)                                     # convert bs from string to float
    print "%s %d %f\n" %(e.name, e.age, e.bs)
fp.close()
Suresh 24 1250.500000

Ranjan 21 1300.600000

Harish 28 1400.700000

EXAMPLE ON PAGE:411-414

In [23]:
 
class emp():
    def __init__(self,**kwds):
        self.__dict__.update(kwds)
e=emp()
try:
    fp=open('EMP.txt','rb+')                             # open the file for reading
except:
    try:
        fp=open('EMP.txt','wb+')                             # open the file for writing
    except:
        print 'cannot open file'
while 1:
    print "1.Add Records"
    print "2.List Records"
    print "3.Modify Records"
    print "4.Delete Records"
    print "0.Exit"
    print "Your choice"
    choice=eval(raw_input())
    def add():
        import os
        fp.seek(0,os.SEEK_END)
        another='Y'
        while another=='Y':
            print "\nEnter name,age and basic salary:"
            e.name=raw_input()
            e.age=eval(raw_input())
            e.bs=eval(raw_input())
            ch="%s %d %f\t\t\t\t\t\t\t\t\t\t" % (e.name,e.age,e.bs)
            fp.writelines("\n")
            fp.writelines(ch)
            print "Add another record(Y/N)"
            another=raw_input()
    def list():
        import os
        fp.seek(0,os.SEEK_SET)
        for line in fp:                             # iterate over each line
            if len(line)>10:
                e.name, e.age, e.bs = line.split()                     # split it by whitespace
                e.age = int(e.age)                                     # convert age from string to int
                e.bs = float(e.bs)                                     # convert bs from string to float
                print "%s %d %f\t\t\t\t\t\t\t\t\t\t" %(e.name, e.age, e.bs)
    def modify():
        another='Y'
        while another=='Y':
            print "\nEnter name of employee to modify"
            empname=raw_input()
            import os
            fp.seek(0,os.SEEK_SET)
            for line in iter(fp.readline, ''):
                if len(line)>10:
                    e.name, e.age, e.bs=line.split()
                    e.age = int(e.age)                                     # convert age from string to int
                    e.bs = float(e.bs)
                    if(cmp(e.name,empname)==0):
                        c=len(line)
                        print "\nEnter new name,age & bs"
                        e.name=raw_input()
                        e.age=eval(raw_input())
                        e.bs=eval(raw_input())
                        import os
                        fp.seek(-c,os.SEEK_CUR)
                        ch="%s %d %f" % (e.name,e.age,e.bs)
                        fp.writelines("\n")
                        fp.writelines(ch)
                        fp.writelines("\n")
                        break
            print "\nModify another Record(Y/N)"
            another=raw_input()
    def delete():
        another='Y'
        global fp
        while another=='Y':
            print "\nEnter name of employee to delete"
            empname=raw_input()
            ft=open('TEMP.txt','wb')
            import os
            fp.seek(0,os.SEEK_SET)
            for line in fp:
                if len(line)>10:
                    e.name, e.age, e.bs=line.split()
                    e.age = int(e.age)                                     # convert age from string to int
                    e.bs = float(e.bs)
                    if(cmp(e.name,empname)!=0):
                        ch="%s %d %f\t\t\t\t\t\t\t\t\t\t" % (e.name,e.age,e.bs)
                        ft.writelines(ch)
                        ft.writelines("\n")
            fp.close()
            ft.close()
            import os
            os.remove("EMP.txt")                           # Delete file EMP.txt
            os.rename( "TEMP.txt", "D:/EMP.txt" )          # Rename a file from TEMP.txt to EMP.txt
            fp=open('EMP.txt','rb+')
            print "Delete another record(Y/N)"
            another=raw_input()
    def exit():
        import sys
        fp.close()
        sys.exit(0)
    def switch(c):
        return {1: add,
                2: list,
                3: modify,
                4: delete,
                0: exit,
                }[c]()
    switch(choice)
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
2
Suresh 24 1250.500000										
Ranjan 21 1300.600000										
Harish 28 1400.700000										
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
1

Enter name,age and basic salary:
Ram
20
5000
Add another record(Y/N)
Y

Enter name,age and basic salary:
GOPAL
19
6755.5
Add another record(Y/N)
N
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
2
Suresh 24 1250.500000										
Ranjan 21 1300.600000										
Harish 28 1400.700000										
Ram 20 5000.000000										
GOPAL 19 6755.500000										
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
3

Enter name of employee to modify
Ram

Enter new name,age & bs
Radhey
15
4687.66

Modify another Record(Y/N)
N
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
2
Suresh 24 1250.500000										
Ranjan 21 1300.600000										
Harish 28 1400.700000										
Radhey 15 4687.660000										
GOPAL 19 6755.500000										
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
4

Enter name of employee to delete
Radhey
Delete another record(Y/N)
N
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
2
Suresh 24 1250.500000										
Ranjan 21 1300.600000										
Harish 28 1400.700000										
GOPAL 19 6755.500000										
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
4

Enter name of employee to delete
GOPAL
Delete another record(Y/N)
N
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
2
Suresh 24 1250.500000										
Ranjan 21 1300.600000										
Harish 28 1400.700000										
1.Add Records
2.List Records
3.Modify Records
4.Delete Records
0.Exit
Your choice
0
An exception has occurred, use %tb to see the full traceback.

SystemExit: 0
To exit: use 'exit', 'quit', or Ctrl-D.

EXAMPLE ON PAGE:416-417

In [24]:
 
from StringIO import StringIO
buffer = StringIO()
print "\nEnter source file name"
source=raw_input()
try:
    inhandle=open(source,'rb')
except:
    print "Cannot open file"
print "Enter target file name"
target=raw_input()
try:
    outhandle=open(target,'wb')
except:
    print "Cannot open file"
    inhandle.close()
bytes=inhandle.readlines()
buffer.write(bytes)
outhandle.writelines(buffer.getvalue())
buffer.close()
inhandle.close()
outhandle.close()
Enter source file name
H4CK3R.txt
Enter target file name
python.txt