Chapter 12: File Input/Output

Display Contents of a File , Page number: 417

In [1]:
fp = open ("C:/Users/Akshatha M/Desktop/carrot.txt", "r" )  #open file in read mode
while ( 1 ):
    ch = fp.read(1)
    if not ch :
        break
    print  ch

fp.close() #close file
M
e
t
h
o
d


T
h
r
o
u
g
h
l
y
 
w
a
s
 
b
o
t
h
 
b
e
e
t
r
o
o
t
 
a
n
d
 
c
a
r
r
o
t
 
t
o
 
r
e
m
o
v
e
 
t
h
e
 
m
u
d
 
o
n
 
b
e
e
t
r
o
o
t
 
a
n
d
 
t
h
e
 
h
a
i
r
 
o
n
 
c
a
r
r
o
t


P
e
e
l
 
o
f
f
 
t
h
e
 
c
a
r
r
o
t
 
s
k
i
n
.
 
d
o
 
n
o
t
 
p
e
e
l
 
t
h
e
 
r
a
d
d
i
s
h
 
s
k
i
n
 
t
o
 
a
v
o
i
d
 
p
o
s
s
i
b
l
e
 
l
o
s
s
 
o
f
 
v
i
t
a
m
i
n
s


C
u
t
 
e
a
c
h
 
b
e
e
t
r
o
o
t
 
a
n
d
 
c
a
r
r
o
t
 
i
n
 
t
o
 
4
 
h
a
l
v
e
s


P
r
e
a
s
s
u
r
e
 
c
o
o
k
 
t
h
e
 
b
e
e
t
r
o
o
t
 
a
n
d
 
c
a
r
r
o
t
.
 
m
a
k
e
 
3
 
w
h
i
s
t
l
e
s
 
s
o
 
t
h
e
t
 
t
h
e
y
 
b
e
c
o
m
e
 
v
e
r
y
 
s
m
o
o
t
h


D
r
a
i
n
 
a
n
d
 
r
e
s
e
r
v
e
 
t
h
e
 
w
a
t
e
r
 
a
f
t
e
r
 
p
r
e
s
s
u
r
e
 
c
o
o
k
i
n
g
.


M
a
s
h
 
t
h
e
 
c
o
o
k
e
d
 
p
i
e
c
e
s
 
a
n
d
 
a
l
l
o
w
 
t
o
 
c
o
o
l


C
u
t
 
o
n
i
o
n
s
 
i
n
t
o
 
c
u
b
e
s
 
a
n
d
 
s
a
u
t
e
 
t
i
l
l
 
g
o
l
d
e
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e
s

Opening a File , Page number: 421

In [*]:
try :
    fp = open ("C:/Users/Akshatha M/Desktop/carrot.txt", "r" )#open file in read mode and check if file is opened successfully
except:
    print  "cannot open file" 
    exit()
cannot open file

Counting Characters,Tabs,Spaces and Newlines , Page number: 423

In [2]:
#Variable declaration
nol = 0
Not = 0
nob = 0
noc = 0

fp = open ("C:/Users/Akshatha M/Desktop/carrot.txt", "r" )  #open file in read mode
while ( 1 ):
    ch = fp.read(1)
    if not ch :
        break
    noc = noc + 1 #number of chars
    if ( ch == " " ):
        nob = nob + 1 #number of spaces
    if ( ch == "\n" ):
        nol = nol + 1 # number of newlines
    if ( ch == "\t" ):
        Not = Not + 1 #number of tabs

fp.close() #close file

#Result
print "Number of characters = ", noc 
print  "Number of blanks = ", nob 
print  "Number of tabs = ", Not 
print  "Number of lines = ", nol 
Number of characters =  1495
Number of blanks =  254
Number of tabs =  0
Number of lines =  20

File Copy , Page number: 424

In [3]:
fs = open ("C:/Users/Akshatha M/Desktop/carrot.txt", "r" )  #open file in read mode
if(not fs):
    print "Cannot open source file"
    exit()

ft = open ( "C:/Users/Akshatha M/Desktop/temp.txt", "w" ) #open file in write mode
if(not ft):
    print "Cannot open target file"
    fs.close()    
    exit()
    
while ( 1 ):
    ch = fs.read(1)
    if not ch :
        break
    else:
        ft.writelines(ch) #write into target file

#closen files
fs.close()
ft.close()

Writing Strings to Files, Page number: 427

In [5]:
fp = open ( "C:/Users/Akshatha M/Desktop/temp.txt", "w" ) #open file in write mode
if(not fp):
    print "Cannot open target file"  
    exit()

print  "Enter a few lines of text:" 
#s=input("") #Input strings from keyboard
s = "File written"
print s
while ( len(s) > 0 ):
    fp.writelines(s) #write into file
    fp.writelines("\n")
    #s=input("") #Input strings from keyboard
    s=""
    
#close files
fp.close()
Enter a few lines of text:
File written

Reading Strings from Files , Page number: 429

In [6]:
fp = open ("C:/Users/Akshatha M/Desktop/carrot.txt", "r" )  #open file in read mode
if ( not fp ):
    print "Cannot open file" 
    exit( ) 

while ( 1 ) :#Read strings from file
    s = fp.read(79)
    if(s):
        print s
    else:
        break
            

fp.close() #close file
Method
Throughly was both beetroot and carrot to remove the mud on beetroot and
 the hair on carrot
Peel off the carrot skin. do not peel the raddish skin to a
void possible loss of vitamins
Cut each beetroot and carrot in to 4 halves
Prea
ssure cook the beetroot and carrot. make 3 whistles so thet they become very sm
ooth
Drain and reserve the water after pressure cooking.
Mash the cooked pieces
 and allow to cool
Cut onions into cubes and saute till golden brown on oil and
 allow to cool
After cooling grind the mashed beetroot, carrot and sauted onion
s to paste in a mixy. add enough water to make paste not very fine.
Now strain 
the grind paste.
Take some butter in a vessel add the garlic paste,gingerpaste 
and green chilli paste and saute for some time till u get the specific garlic-b
eing-fried smell
Add moong sprouts and saute, cover with the lid and let cook f
or 5 mins
Now add the strain of beetroot,carrot and onions paste
Add 6 cups of 
water to it and also the water reserved at the time of pressure cooking the bee
troot and carrot.
Add salt, cinnamon, cummin, coriander powder,lemon juice
Brin
g to a boil, let simmer for a few mins
Make a fine paste of cornflour and add i
t while stirring to avoid lumps
Til for somemore time so that the cornflour pas
te is cooked and mixed well
Take oil in a kadhai to fry the noodles.fry till go
lden brown and reserve on a tissue paper
Crush the noodles not too much
Serve s
teaming hot in soup bowls add some butter and top with the crispy noodles

Writing Records to Files , Page number: 431

In [9]:
from collections import namedtuple

#Variable declaration
another = 'Y'

#Structure defintion
struct_emp = namedtuple("struct_emp", "name age bs")


fp = open ( "C:/Users/Akshatha M/Desktop/Employee.dat", "w" ) #open file in write mode
if(not fp):
    print "Cannot open target file"
    exit()

while ( another == 'Y' ):
    print  "Enter name, age and basic salary: " 
    #en,ea,ebs = input("").split()
    en ="John"
    ea="34"
    ebs="25000"
    print en,ea,ebs
    e = struct_emp(en,ea,ebs)
    fp.writelines(e) #write into file
    fp.writelines("\n")
    #another = input( "Add another record (Y/N): " )  
    print "Add another record (Y/N): "
    another = 'N'
    print another
#close file
fp.close()
Enter name, age and basic salary: 
John 34 25000
Add another record (Y/N): 
N

Reading Records from File , Page number: 433

In [11]:
from collections import namedtuple
#Structure defintion
struct_emp = namedtuple("struct_emp", "name age bs")


fp = open ( "C:/Users/Akshatha M/Desktop/Employee.txt", "r" ) #open file in read mode
if(not fp):
    print "Cannot open target file"
    exit()

while ( 1 ):
    s = fp.readline()
    if(s):
        en,ea,ebs = s.split()
        e = struct_emp(en,ea,ebs) #Read record
        print  e.name, e.age, e.bs 
    else:
        break
    
#close file
fp.close()
John 34 25000

Copying Binary Files , Page number: 434

In [12]:
fs = open ("C:/Users/Akshatha M/Desktop/Project1.exe", "rb" )  #open file in read binary mode
if(not fs):
    print "Cannot open source file"
    exit()

ft = open ( "C:/Users/Akshatha M/Desktop/NewProject1.exe", "wb" ) #open file in write binary mode
if(not ft):
    print "Cannot open target file"
    fs.close()    
    exit()
    
while ( 1 ):
    ch = fs.read(1)
    if not ch :
        break
    else:
        ft.write(ch) #write into target file

#closen files
fs.close()
ft.close()

Writing To Files in Binary Mode, Page number: 438

In [13]:
from collections import namedtuple

#Variable declaration
another = 'Y'

#Structure defintion
struct_emp = namedtuple("struct_emp", "name age bs")

fp = open ( "C:/Users/Akshatha M/Desktop/Employee.dat", "wb" ) #open file in write mode
if(not fp):
    print "Cannot open target file"  
    exit()

while ( another == 'Y' ):
    print ( "Enter name, age and basic salary: " )
    #en,ea,ebs = input("").split()
    en ="John"
    ea="34"
    ebs="25000"
    print en,ea,ebs
    e = struct_emp(en,ea,ebs)
    #write into file
    fp.write(b'e.name')
    fp.write(b'e.age')
    fp.write(b'e.bs')
    fp.write(b'\n')
    #another = input( "Add another record (Y/N): " )  
    print "Add another record (Y/N): "
    another = 'N'
    print another

#close file
fp.close()
Enter name, age and basic salary: 
John 34 25000
Add another record (Y/N): 
N

Reading From Binary Files , Page number: 440

In [14]:
from collections import namedtuple
#Structure defintion
struct_emp = namedtuple("struct_emp", "name age bs")


fp = open ( "C:/Users/Akshatha M/Desktop/Employee.txt", "rb" ) #open file in read mode
if(not fp):
    print "Cannot open target file" 
    exit()

while ( 1 ):
    s = fp.readline()
    if(s):
        en,ea,ebs = s.split()
        e = struct_emp(en,ea,ebs) #Read record
        print  e.name, e.age, e.bs 
    else:
        break
    
#close file
fp.close()
John 34 25000

Database Management, Page number: 442

In [ ]:
import os
from collections import namedtuple
#Structure defintion
struct_emp = namedtuple("struct_emp", "name age bs")

fp = open ( "C:/Users/Akshatha M/Desktop/Employee.txt", "r+b")
if ( not fp ):
    fp = open ( "C:/Users/Akshatha M/Desktop/Employee.txt", "w+b" )
    if ( not fp ):
        print  "Cannot open file" 
        exit( )

while ( 1 ):
    print  "   1. Add Records"
    print "   2. List Records"
    print "   3. Modify Records"
    print "   4. Delete Records" 
    print "   0. Exit" 
    #choice = input("\nYour choice")
    print "\nYour choice"
    choice = 1
    if(choice == '1'):
        another = 'Y'
        while ( another == 'Y' ):
            print ( "Enter name, age and basic salary: " )
            en,ea,ebs = input("").split()
            e = struct_emp(en,ea,ebs)
            #write into file
            fp.write(b'e.name')
            fp.write(b' ')
            fp.write(b'e.age')
            fp.write(b' ')
            fp.write(b'e.bs')
            fp.write(b'\n')
            another = input( "Add another record (Y/N): " )
    elif(choice == '2'):
        fp.seek(0,0)
        while ( 1 ):
            s = fp.readline()
            if(s):
                en,j1,ea,j2,ebs = s.split()
                e = struct_emp(en,ea,ebs) #Read record
                print ( e.name, e.age, e.bs )
            else:
                break
    elif(choice == '3'):
        another = 'Y'
        while ( another == 'Y' ):
            empname =input("Enter name of employee to modify " )
            fp.seek(0,0)
            while (fp.readline()):
                if ( b'empname' == b'e.name' ):
                    en,ea,ebs = input("Enter new name, age & bs" ).spilt()
                    e = struct_emp(en,ea,ebs)
                    cur = fp.tell()
                    fp.write(b'e.name')
                    fp.write(b'e.age')
                    fp.write(b'e.bs')
                    fp.write(b'\n')
                    break
            print ( "\nModify another Record (Y/N) " )
            another = input("")
    elif(choice == '4'):
        another = 'Y'
        while ( another == 'Y' ):
            empname = input("Enter name of employee to delete " )
            ft = open ( "C:/Users/Akshatha M/Desktop/temp.txt", "wb" )
            fp.seek(0,0)
            while ( 1 ):
                s = fp.readline()
                if(s):
                   if ( not(b'empname' == b'e.name' )):
                        ft.write(s)
                else:
                    break
            fp.close()
            ft.close()
            os.remove("C:/Users/Akshatha M/Desktop/Employee.txt")
            os.rename ( "C:/Users/Akshatha M/Desktop/temp.txt", "C:/Users/Akshatha M/Desktop/Employee.txt" )
            fp = open ( "C:/Users/Akshatha M/Desktop/Employee.txt", "r+b" )
            print ( "Delete another Record (Y/N) " )
            another = input("")

    else:
        fp.close()#close file
        exit( )

Low Level File Copy, Page number: 448

In [16]:
#source=input( "Enter source file name " ) 
print "Enter source file name " 
source = "Employee.txt"
print source
source="C:/Users/Akshatha M/Desktop/"+source

inhandle = open (source, "rb" )  #open file in read binary mode
if(not inhandle):
    print "Cannot open file"
    exit()

#target=input( "Enter target file name " ) 
print "Enter target file name "
target = "temp.txt"
print target
target="C:/Users/Akshatha M/Desktop/"+target

outhandle = open ( target, "wb" ) #open file in write binary mode
if(not outhandle):
    print "Cannot open target file"
    inhandle.close()    
    exit()


    
while ( 1 ):
    Bytes = inhandle.read(1)
    if not Bytes :
        break
    else:
        outhandle.write(Bytes) #write into target file

#closen files
inhandle.close()
outhandle.close()
Enter source file name 
Employee.txt
Enter target file name 
temp.txt

Detecting Errors in Reading/Writing, Page number: 470

In [1]:
fp = open ( "C:/Users/Akshatha/Documents/extrastuff/skills.txt", "w" ) 
while (1):
    try:
        ch = fp.read(1) #read character from file 
    except: #ferror()
        print  "Error in reading file" 
        break 
    print ch 
    
fp.close()
Error in reading file

Standard IO devices, Page number: 472

In [5]:
import io

try:
    fp = open ("C:/Users/Akshatha/Documents/extrastuff/skills.txt", "r")
except:
    print "cannot open file"
    exit()
 
io.open('stdprn','w')          
try:
    stdprn = io.open('stdprn', 'w') #open printer

    while ( 1 ):
        ch = fp.read(1)
        if not ch :
            break
        else:
            stdprn.write(ch) #write into printer
except: #no printer
    #closen files
    fp.close()
    stdprn.close()
    
In [ ]: