Chapter 22: File Operations

Example canopen.c, Page 547

In [1]:
try:
    fname=raw_input()
    fp=open('noexist',r)
except:
    print "Can't be opened"
else:
    print "Can be opened"
file
Can't be opened

Example fcopy.c, Page 568

In [1]:
try:
    s=raw_input("Source")
    d=raw_input("Destination")
    source_fp=open(s,'rb')
    dest_fp = open(d,wb)

    for line in source_fp.readlines():
        dest_fp.write(line)   

    dest_fp.close()
    source_fp.close()
except:
    print "Can't be opened"
Sourcef1
Destinationf2
Can't be opened

Example invclear.c, Page 574

In [ ]:
NAME_LEN=25
max_parts=100
char name=None*(NAME_LEN+1)
on_hand=list()
try:
    fp=open('inventory.dat','r')
except:
    print "Cant open inventory file"
num_parts=fp.read()
for i in range (num_parts):
    on_hand[i]=0
fp.seek(0,0)
fp.write(on_hand)
fp.close
In [ ]: