Chapter 12: Files

Example 12.1, Page number: 428

In [12]:
# Calculation and result
fp = open('12.1.dat', 'w')

for i in range (0, 11) :
	fp.write('%d, %d \n' % (i, i*i))
fp.close()

Example 12.2, Page number: 429

In [13]:
# Calculation and result
fp = open('12.2.dat', 'w')

for i in range (0, 11) :
	fp.write('%d, %d \n' % (i, i*i))
fp.close()

Example 12.3, Page number: 430

In [1]:
# Calculation and result
fp = open('12.2.dat', 'a')
i = 11
fp.write('%d, %d \n' % (i, i*i))
fp.close()

Example 12.4, Page number: 432

In [15]:
# Calculation and result
with open ('12.2.dat') as fp:
	for line in fp :
		print line
fp.close()
0, 0 

1, 1 

2, 4 

3, 9 

4, 16 

5, 25 

6, 36 

7, 49 

8, 64 

9, 81 

10, 100 

Example 12.5, Page number: 434

In [16]:
# Calculation and result
print ('Data input ')
f1 = open('12.5.dat', 'w')
f1.write('You are learning Files in Python language ')
f1.close()

print ('Data output ')
with open ('12.5.dat') as f1:
	for line in f1 :
		print line
f1.close()
Data input 
Data output 
You are learning Files in Python language 

Example 12.6, Page number: 435

In [17]:
# Calculation and result
print ('Contents of the data file ')
f1 = open('12.6.dat', 'w')
for i in range (0, 10) :
	number = int(raw_input())
	f1.write('%d\n' % number)
f1.close()

f1 = open('12.6.dat', 'r')
f2 = open('12.6o.dat', 'w')
f3 = open('12.6e.dat', 'w')

num = [0] * 10
with open ('12.6.dat') as f1 :
	num = f1.read().splitlines()
	
for i in range (0, 10) :
	if (int(num[i]) % 2) != 0 :
		f2.write('%s \n' % (num[i]))
	else :
		f3.write('%s \n' % (num[i]))
	
f1.close()
f2.close()
f3.close()

print ('Contents of the odd file ')
with open ('12.6o.dat') as f2:
	for line in f2 :
		print line

print ('Contents of the even file ')
with open ('12.6e.dat') as f3:
	for line in f3 :
		print line

f2.close()
f3.close()
Contents of the data file 
1
2
3
4
5
6
7
8
9
10
Contents of the odd file 
1 

3 

5 

7 

9 

Contents of the even file 
2 

4 

6 

8 

10 

Example 12.7, Page number: 438

In [18]:
# Calculation and result
filename = raw_input('Input filename: ')
fp = open(filename, 'w')

print ('Input inventory data ')
print ('\nItemName number price quantity ')

data = [[0 for y in xrange(5)] for x in xrange(3)]
for i in range (0, 3) :
	for j in range (0, 4) :
		data[i][j] = raw_input('')
		fp.write('%s  ' % data[i][j]),
	fp.write('\n')
	print
fp.close()

fp = open(filename, 'r')

for i in range (0, 3) :
	for j in range (2, 3) :
		data[i][j+2] = float(data[i][j]) * int(data[i][j+1])

print ('ItemName   number   price   quantity   value ')
for i in range (0, 3) :
	for j in range (0, 5) :
		print ('%8s' % data[i][j]),
	print
Input filename: 12.7.dat
Input inventory data 

ItemName number price quantity 
Monitor
11
3005.50
10

Mouse
22
500.50
5

Keyboard
33
750.00
10

ItemName   number   price   quantity   value 
 Monitor       11  3005.50       10  30055.0
   Mouse       22   500.50        5   2502.5
Keyboard       33   750.00       10   7500.0

Example 12.8, Page number: 440

In [19]:
# Calculation and result
with open ('12.5.dat') as fp:
	for line in fp :
		print line
fp.close()
You are learning Files in Python language 

Example 12.9, Page number: 441

In [ ]:
from sys import argv

# Calculation and result
script, filename = argv
file = open(filename)
print file.read()
print ('\nFile displayed successfully.....')
In [20]:
%run 12.9.py 12.1.dat
0, 0 
1, 1 
2, 4 
3, 9 
4, 16 
5, 25 
6, 36 
7, 49 
8, 64 
9, 81 
10, 100 


File displayed successfully.....

Example 12.10, Page number: 444

In [21]:
# Calculation and result
class person (object) :
	def __init__(self, name = None, age = 0):
		self.name = 0
		self.age = 0
		
data = [person() for i in range (5)]

fp = open('12.10.dat','w')

for i in range (0, 5) :
	data[i].name = raw_input('\nEnter name : ')
	data[i].age = int(raw_input('Enter age : '))
	
for i in range (0, 5) :
	fp.write('%s %d \n' % (data[i].name, data[i].age))

print ('\n...Records are written to a file...')
print ('...Displaying records from a file...')

for i in range (0, 5) :
	print ('\nName : %s ' % data[i].name)
	print ('Age : %d ' % data[i].age)
Enter name : Dhiraj Kumar
Enter age : 23

Enter name : Mohasin Khan
Enter age : 45

Enter name : Suresh Waghmare
Enter age : 55

Enter name : Anand Rao
Enter age : 34

Enter name : Sunil Deshpande
Enter age : 23

...Records are written to a file...
...Displaying records from a file...

Name : Dhiraj Kumar 
Age : 23 

Name : Mohasin Khan 
Age : 45 

Name : Suresh Waghmare 
Age : 55 

Name : Anand Rao 
Age : 34 

Name : Sunil Deshpande 
Age : 23 

Example 12.11, Page number: 445

In [11]:
# Calculation and result
class record (object) :
	def __init__(self, name = None, age = 0) :
		self.name = 0
		self.age = 0
		
def record_write (data, filename) :
	filep = open(filename, 'ab')
	data.name = raw_input('Enter name : ')
	data.age = int(raw_input('Enter age : '))
	filep.write('%s %d\n' % (data.name, data.age))
	
def record_readall (filename) :
	print
	with open (filename) as filep :
		for line in filep :
			print line

data = record ()
filename = '12.11.dat'

condition = True
while condition :
	enter = raw_input('\nAdd record (y/n) ? ')
	if enter == 'y' or enter == 'Y' :
		record_write (data, filename)
	else :
		condition = False
		break

record_readall (filename)
Add record (y/n) ? y
Enter name : Mohan Pande
Enter age : 34

Add record (y/n) ? y
Enter name : Nitin Dighe
Enter age : 32

Add record (y/n) ? n

Mohan Pande 34

Nitin Dighe 32

Example 12.12, Page number: 449

In [22]:
# Calculation and result
fp = open('12.12.txt','r')
fp.seek(0, 0)
line = fp.readline()
print ('Read Line: %s ' % line)

fp.seek(17, 0)
line = fp.readline()
print ('Read Line: %s ' % line)
Read Line: This is 1st line
 
Read Line: This is 2nd line
 

Example 12.13, Page number: 449

In [23]:
import os

# Calculation and result
statinfo = os.stat('12.13.txt')
print ('Filesize of "12.13.txt" is %d bytes ' % statinfo.st_size)
Filesize of "12.13.txt" is 15 bytes 

Example 12.14, Page number: 455

In [9]:
# Calculation and result
nc = nlines = 0

filename = raw_input('Enter file name: ')
with open(filename, 'r') as fp :
    for line in fp :
        nlines += 1
        nc += len(line)
fp.close()

print ('There are %d characters in %s ' % (nc, filename))
print ('There are %d lines ' % nlines)
Enter file name: 12.14.txt
There are 55 characters in 12.14.txt 
There are 1 lines 

Example 12.15, Page number: 456

In [1]:
# Calculation and result
linecount = 0
filename = raw_input('Enter file name: ')
fp = open(filename, 'r')
for line in fp :
	print line
	linecount += 1
	if linecount % 20 == 0 :
		raw_input("[Press Return to continue, Q to quit]")
		if raw_input() == 'Q' :
			exit()
Enter file name: 12.15.txt
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

[Press Return to continue, Q to quit]Q

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

[Press Return to continue, Q to quit]

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

[Press Return to continue, Q to quit]

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

[Press Return to continue, Q to quit]

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

[Press Return to continue, Q to quit]

Example 12.16, Page number: 457

In [3]:
# Calculation and result
fname1 = raw_input('Enter source file: ')
fname2 = raw_input('Enter destination file: ')

with open(fname1) as fp1 :
	with open(fname2,'w') as fp2 : 
		for line in fp1 :
			fp2.write(line)

print ('Files successfully copied ')
Enter source file: 12.16in.txt
Enter destination file: 12.16out.txt
Files successfully copied 

Example 12.17, Page number: 458

In [1]:
# Calculation and result
total = count = 0
filenameIn = raw_input('Please enter an input filename: ')
filenameOut = raw_input('Please enter an output filename: ')

print ('Opening %s for reading is OK.' % filenameIn)
print ('Opening %s for writing is OK.' % filenameOut)
print ('Calculate the total...')

for i in open(filenameIn) :
	count += 1
	total += int(i.strip())
	
print ('Calculate the average...')
fileptrOut = open(filenameOut,'w')
fileptrOut.write('Average of %d numbers = %f ' % (count, (total/count)))

print ('Check also your %s file content ' % filenameOut)
fileptrOut.close()
print ('"%s" closed successfully ' % filenameIn)
print ('"%s" closed successfully ' % filenameOut)
Please enter an input filename: 12.17in.dat
Please enter an output filename: 12.17out.dat
Opening 12.17in.dat for reading is OK.
Opening 12.17out.dat for writing is OK.
Calculate the total...
Calculate the average...
Check also your 12.17out.dat file content 
"12.17in.dat" closed successfully 
"12.17out.dat" closed successfully 

Example 12.18, Page number: 460

In [10]:
# Structure declaration
class STUDENT (object) :
	def __init__(self, fname=None, lname=None, id=None, quiz1=None, quiz2=None, quiz3=None, quiz4=None, exam=None) :
		self.fname = fname
		self.lname = lname
		self.id = id
		self.quiz1 = quiz1
		self.quiz2 = quiz2
		self.quiz3 = quiz3
		self.quiz4 = quiz4
		self.exam = exam
	
def findLow (students, x, c) :
	if x == 0 :
		small = students[0].quiz1
		for i in range (1, c) :
			if small >= students[i].quiz1 and students[i].quiz1 > 0 :
				small = students[i].quiz1
		return small
		
	elif x == 1 :
		small = students[0].quiz2
		for i in range (1, c) :
			if small >= students[i].quiz2 and students[i].quiz2 > 0 :
				small = students[i].quiz2
		return small
		
	elif x == 2 :
		small = students[0].quiz3
		for i in range (1, c) :
			if small >= students[i].quiz3 and students[i].quiz3 > 0 :
				small = students[i].quiz3
		return small

	elif x == 3 :
		small = students[0].quiz4
		for i in range (1, c) :
			if small >= students[i].quiz4 and students[i].quiz4 > 0 :
				small = students[i].quiz4
		return small
		
	elif x == 4 :
		small = students[0].exam
		for i in range (1, c) :
			if small >= students[i].exam and students[i].exam > 0 :
				small = students[i].exam
		return small
	return 0

def findHigh (students, x, c) :
	if x == 0 :
		big = students[0].quiz1
		for i in range (1, c) :
			if big <= students[i].quiz1 :
				big = students[i].quiz1
		return big
		
	elif x == 1 :
		big = students[0].quiz2
		for i in range (1, c) :
			if big <= students[i].quiz2 :
				big = students[i].quiz2
		return big
		
	elif x == 2 :
		big = students[0].quiz3
		for i in range (1, c) :
			if big <= students[i].quiz3 :
				big = students[i].quiz3
		return big

	elif x == 3 :
		big = students[0].quiz4
		for i in range (1, c) :
			if big <= students[i].quiz4 :
				big = students[i].quiz4
		return big
		
	elif x == 4 :
		big = students[0].exam
		for i in range (1, c) :
			if big <= students[i].exam :
				big = students[i].exam
		return big
	return 0


students = [STUDENT() for i in range (5)]
summ = avg = low = high = [0] * 5
cnt = 0

print ('--- CLASS INFO --- \n')
print ('Name\t\t Id\tQuiz1   Quiz2   Quiz3   Quiz4   Exam \n')

with open('12.18.txt') as fpr :
	for line in fpr :
		i = 0
		students[i].fname, students[i].lname, students[i].id, students[i].quiz1, students[i].quiz2, students[i].quiz3, students[i].quiz4, students[i].exam = line.split()
		students[i].id = int(students[i].id)
		students[i].quiz1 = int(students[i].quiz1)
		students[i].quiz2 = int(students[i].quiz2)
		students[i].quiz3 = int(students[i].quiz3)
		students[i].quiz4 = int(students[i].quiz4)
		students[i].exam = int(students[i].exam)
		
		print ('%-s %-s\t %-4d	%-3d	%-3d	%-3d	%-3d	%-3d' % (students[i].fname, students[i].lname, students[i].id, students[i].quiz1, students[i].quiz2, students[i].quiz3, students[i].quiz4, students[i].exam)) 
		
		summ[0] += int(students[i].quiz1)
		summ[1] += int(students[i].quiz2)
		summ[2] += int(students[i].quiz3)		
		summ[3] += int(students[i].quiz4)
		summ[4] += int(students[i].exam)
		i = i+1
		cnt = cnt+1

print ('\nSTATISTICS')
print ('\t\tQuiz1	Quiz2	Quiz3	Quiz4	Exam\n')
print ('Average:\t'),
for i in range (0, 5) :
	avg[i] = float(summ[i])/cnt
	print ('%-5.1f \t' % avg[i]),
print

print ('Lowest:\t\t'),
for i in range (0, 5) :
	low[i] = findLow (students, i, cnt)
	high[i] = findHigh (students, i, cnt)
	
for i in range (0, 5) :
	print ('%-5d \t' % low[i]),
print
	
print ('Highest:\t'),
for i in range (0, 5) :
	print ('%-5d \t' % high[i]),
print

print ('\n --- END OF REPORT --- \n')
--- CLASS INFO --- 

Name		 Id	Quiz1   Quiz2   Quiz3   Quiz4   Exam 

anand mane	 11  	10 	3  	4  	5  	80 
mandar patil	 12  	4  	5  	6  	7  	50 
kishoe dhane	 13  	4  	5  	6  	8  	55 

STATISTICS
		Quiz1	Quiz2	Quiz3	Quiz4	Exam

Average:	6.0   	4.3   	5.3   	6.7   	61.7  	
Lowest:		4     	5     	6     	8     	55    	
Highest:	4     	5     	6     	8     	55    	

 --- END OF REPORT --- 

Example 12.19, Page number: 466

In [6]:
import sys

# Structure declaration
class Employee (object) :
	def __init__(self, fname=None, lname=None, sub_taken=None, last_edu=None, join_date=None, id=None, age=None, bsal=None) :
		self.fname = fname
		self.lname = lname
		self.sub_taken = sub_taken
		self.last_edu = last_edu
		self.join_date = join_date
		self.id = id
		self.age = age
		self.bsal = bsal
	
emp = Employee ()
fp = open('12.19.dat','ab+')
recsize = sys.getsizeof(emp)

condition = True
while condition :
	print ('\n1.Add Records \
			  \n2.Delete Records \
			  \n3.Modify Records \
			  \n4.List Records \
			  \n5.Exit')
	choice = int(raw_input('\nEnter your choice: '))
	
	if choice == 1 :
		another = 'Y'
		while another == 'Y' or another == 'y' :
			fp = open('12.19.dat','ab+')
			emp.fname = raw_input('Enter the first name: ')
			emp.lname = raw_input('Enter the last name: ')
			emp.age = int(raw_input('Enter the age: '))
			emp.bsal = int(raw_input('Enter the basic salary: '))
			emp.join_date = int(raw_input('Enter joining date: '))
			emp.id = int(raw_input('Enter the employee id: '))
			emp.last_edu = raw_input('Enter the last education: ')
			emp.sub_taken = raw_input('Enter the subject taken: ')
			fp.write('%d %s %s %d %d %s %s %s \n' % (emp.id, emp.fname, emp.lname, emp.age, emp.bsal, emp.join_date, emp.last_edu, emp.sub_taken))
			another = raw_input('Add another record (Y/N) ? ')

	elif choice == 2 :
		another = 'Y'
		while another == 'Y' or another == 'y' :
			fp = open('12.19.dat','r')
			lines = fp.readlines()
			lines = lines[:-1]
			print ('\nRecord deleted ')
			another = raw_input('Delete another record (Y/N) ? ')
		
	elif choice == 3 :
		fp = open('12.19.dat','w')
		another = 'Y'
		while another == 'Y' or another == 'y' :
			emp.fname = raw_input('Enter the first name: ')
			emp.lname = raw_input('Enter the last name: ')
			emp.age = int(raw_input('Enter the age: '))
			emp.bsal = int(raw_input('Enter the basic salary: '))
			emp.join_date = int(raw_input('Enter joining date: '))
			emp.id = int(raw_input('Enter the employee id: '))
			emp.last_edu = raw_input('Enter the last education: ')
			emp.sub_taken = raw_input('Enter the subject taken: ')
			fp.write('%d %s %s %d %d %s %s %s \n' % (emp.id, emp.fname, emp.lname, emp.age, emp.bsal, emp.join_date, emp.last_edu, emp.sub_taken))
			another = raw_input('Modify another record (Y/N) ? ')
	 	
	elif choice == 4 :
		with open ('12.19.dat','r') as fp :
			for line in fp :
				print line
		
	elif choice == 5 :
		condition = False
		fp.close()
		exit()
1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 1
Enter the first name: Anand
Enter the last name: Rao
Enter the age: 29
Enter the basic salary: 5000
Enter joining date: 2004
Enter the employee id: 11
Enter the last education: BCA
Enter the subject taken: OS
Add another record (Y/N) ? y
Enter the first name: Deepti
Enter the last name: Garg
Enter the age: 22
Enter the basic salary: 25000
Enter joining date: 2014
Enter the employee id: 12
Enter the last education: BTech
Enter the subject taken: CSE
Add another record (Y/N) ? n

1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 4
11 Anand Rao 29 5000 2004 BCA OS 

12 Deepti Garg 22 25000 2014 BTech CSE 


1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 2

Record deleted 
Delete another record (Y/N) ? y

Record deleted 
Delete another record (Y/N) ? n

1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 3
Enter the first name: Nalin
Enter the last name: Chhibber
Enter the age: 25
Enter the basic salary: 30000
Enter joining date: 2012
Enter the employee id: 07
Enter the last education: MTech
Enter the subject taken: DBMS
Modify another record (Y/N) ? n

1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 4
7 Nalin Chhibber 25 30000 2012 MTech DBMS 


1.Add Records 			  
2.Delete Records 			  
3.Modify Records 			  
4.List Records 			  
5.Exit

Enter your choice: 5