Chapter 13: File Handling

Example 13.3, Page 12.4

In [5]:
fp=open("output.txt",'w')
for k in range(65,91):
	fp.write(str(k)+'\n')
fp.close()

Example 13.7, Page 13.8

In [2]:
from ctypes import *

string=c_char*40

class date(Structure):
	_fields_=[('month',c_int),('day',c_int),('year',c_int)]
	
class account(Structure):
	_fields_=[('name',string),('street',string),('city',string),('acct_no',c_int),('oldbalance',c_float),('payment',c_float),('lastpayment',date),('acct_type',c_char),('newbalance',c_float)]


def writefile(obj,fpt):
	fpt.write(obj.name+'\n')
	fpt.write(obj.city+'\n')
	fpt.write(str(obj.acct_no)+'\n')
	fpt.write(obj.acct_type+'\n')
	fpt.write(str(obj.oldbalance)+'\n')
	fpt.write(str(obj.newbalance)+'\n')
	fpt.write(str(obj.payment)+'\n')
	fpt.write(str(obj.lastpayment.month)+' ')
	fpt.write(str(obj.lastpayment.day)+' ')
	fpt.write(str(obj.lastpayment.year)+'\n\n')
	
	return	
	
fpt=open('records.txt','w')


customer=[]

name='Steve Johnson'
street='123 Mountainview Drive '
city='Denver . CO'
acct_no=4208
oldbalance=247.88
payment=25.00
lastpay=date(6,14,1998)
customer.append(account(name,street,city,acct_no,oldbalance,payment,lastpay))

name='Susan Richards'
street='4383 Aligator Blvd'
city='Fort Lauderdale. FL'
acct_no=2219
oldbalance=135.00
payment=135.00
lastpay=date(8,10,2000)
customer.append(account(name,street,city,acct_no,oldbalance,payment,lastpay))

name='Martin Peterson'
street='1787 Pacific Parkway'
city='San Diego. CA'
acct_no=8452
oldbalance=387.42
payment=35.00
lastpay=date(9,22,1999)
customer.append(account(name,street,city,acct_no,oldbalance,payment,lastpay))

name='Phyllis Smith'
street='1000 Great White Way'
city='New York. NY'
acct_no=711
oldbalance=260.00
payment=0.00
lastpay=date(11,27,2001)
customer.append(account(name,street,city,acct_no,oldbalance,payment,lastpay))



for i in range(0,4):
	if customer[i].payment>0:
		if customer[i].payment<0.1*customer[i].oldbalance:
			customer[i].acct_type='O'
		else:
			customer[i].acct_type='C'
	else:
		if customer[i].oldbalance>0:
			customer[i].acct_type='D'
		else:
			customer[i].acct_type='C'
	
	customer[i].newbalance=customer[i].oldbalance-customer[i].payment
	
	writefile(customer[i],fpt)

fpt.close()

Example 13.13, Page 13.28

In [3]:
fp=open('binval.txt','wb')

for i in range(1000,11001):
	fp.write(str(i))

fp.close()
In [ ]: