poem = ["\n\tI never saw a man who looked"]
poem.append("\n\tWith such a wistful eye")
poem.append("\n\tUpon that little tent of blue")
poem.append("\n\tWhich prisoners call the sky")
try:
writer = open("poem.txt","w")
if(not isinstance(writer,file)):
print "Error opening file for output"
writer.writelines(poem)
writer.close()
except IOError:
print "Error opening file for output"
"""
Out put Text File :- poem.txt
I never saw a man who looked
With such a wistful eye
Upon that little tent of blue
Which prisoners call the sky
The Ballad of Reading Gaol
Oscar Wilde 1898
"""
info = "\n\tThe Ballad of Reading Gaol"
info = info + "\n\t\t\tOscar Wilde 1898" #There is no append for string in python
try:
writer = open("poem.txt","a")
if(not isinstance(writer,file)):
print "Error opening file for output"
writer.writelines(info)
writer.close()
except IOError:
print "Error opening file for output"
try:
reader = open("poem.txt","r")
if(not isinstance(reader,file)):
print "Error opening input file"
i = 0
while(1):
c = reader.read(1)
if c == "":
break
else:
print c,
i= i + 1
reader.close()
print "\nIterations: ",i
except IOError:
print "Error opening input file"
# this program gives output same as book program but logic is different because some of functions are not available in python
RANGE = 12
tab = range(RANGE)
i = 0
j = 1
t = ""
try:
reader = open("records.txt","r")
if(not isinstance(reader,file)):
print "Error opening input file"
while(1):
c = reader.read(1)
if c == "":
break
else:
t = t + c
if c == '\t':
tab[i] = t
t = ""
i = i + 1
elif c == '\n':
tab[i] = t
t = ""
i = i + 1
elif i == RANGE-1:
tab[i] = t
reader.close()
i= 0;
while i < RANGE:
print "Record Number: ",j
j = j + 1
print "Forename: ",tab[i]
i = i + 1
print "Surname: ",tab[i]
i = i + 1
print "Department: ",tab[i]
i = i + 1
print "Telephone: ",tab[i]
i = i + 1
except IOError:
print "Error opening input file"
"""
INPUT FILE :- records.txt
John Smith Sales 555-1234
Mary Jones Wages 555-9876
Paul Harris Accts 555-4321
"""
isTrue = 1
num = 255
for i in range(0,40):
print ".",
print "Output"
print "Pi: ","3.1415926536"
print isTrue,":",bool(isTrue)
print num,":","{:01X}".format(num)
try:
for number in range(1,21):
if number > 4:
raise Exception(number)
else:
print "Number: ",number
except:
print "Exception at: ",number
import sys
lang = "C++"
try:
lang.erase(4,6)
except:
print "Exception",sys.exc_info()[0]
# There is no support for erse method in python
#there is no replace or resize method in python
import sys
lang = "C++"
num = 1000000000
try:
lang.replace(lang,"C","1")
lang.resize(3*num)
reader = open("nonsuch.txt","r")
print "Program continues..."
except:
print sys.exc_info()[0]
print "Program terminated."
#python dose not support much more exceptions