In: Computer Science
USE BASIC PYTHON
Focus on Basic file operations, exception handling.
Save a copy of the file module6data.txt (Below)
Write a program that will
a. Open the file module6data.txt
b. Create a second file named processed. txt
c. Read the numbers from the first file one at a time. For each number write into second file, if possible, its
I. Square
ii. Square root
iii. Reciprocal (1/number)use a math module function for the square root. use exception handling to trap possible errors.
d. Report the number of items in the original file and the number that were successfully stored in the second file.
e. Report the number of each type of error: ValueError, ZeroDivisionError, TypeError
26
O
76
-91
85
-44
85
-95
-34
83
-64
-76
-41
89
0
83
-99
-69
8
-79
0
-32
-49
-89
85
79
-28
56
19
-93
-21
-23
82
51
-80
l
62
-78
-8
71
28
-73
0
-45
-73
28
-5
O
-70
63
-36
-72
0
-76
-24
-59
0
-54
83
35
-3
88
-14
29
-35
17
27
-61
-42
49
83
38
79
-80
33
8
41
96
-94
46
71
8
76
-63
-36
93
-82
-68
-20
69
-57
-84
-29
-17
77
36
-89
-94
62
10
-69
-43
RAW CODE
import math
File = open('module6data.txt', 'r') ### Opening File
Lines = File.readlines() ## Reading file line by line
output = open('processed. txt', 'w') ### Opening new file processed.txt
original_count, processed_count = 0, 0 ### Initializing values to 0
ve,te,zde = 0,0,0
for line in Lines:
try:
original_count += 1 ### x += 1 is same as x = x + 1
square, square_root, reciprocal = int(line) ** 2, math.sqrt(int(line)), 1 / int(line) ## math.sqrt() don't work on negative numbers
number = int(line)
output.write("{}: {}, {}, {}\n".format(number, square, square_root, reciprocal)) ## output is saved in format "number: square, square_root, reciprocal" in text file.
processed_count += 1
except ValueError: ### Type of error
ve += 1
except ZeroDivisionError:
zde += 1
except TypeError:
te += 1
output.close() ### closing file
if __name__ == '__main__': ### main function.
print("Number of items in the original file: ",original_count) ### Reporting results
print("Number of items in the processed file: ",processed_count)
print("Number of TypeError: ",te)
print("Number of ValueError: ",ve)
print("Number of ZeroDivisionError: ",zde)
SCREENSHOTS (CODE WITH OUTPUT)
processed.txt file
###### FOR ANY QUERY, KINDLY GET BACK, THANKYOU. ######